跨多个实例共享单个基础对象

在我的 API 设计中,我有这样的东西:


class APIConnection:

    # sets up the session and only contains connection-related methods

    def __init__(self):

        self.session = requests.Session()


    def api_call(self):

        # do session-related stuff



class User(APIConnection):

    def __init__(self, username, password):

        super().__init__()

        # do login stuff, get access token

        # update inherited session with authorization headers

        self.session.headers.update({"Access-Token": access_token})


        self.profile = Profile(profile_data) # set up profile object


class Profile:

    def __init__(self, profile_data):

        pass


    # this is where I would like to get access to the session that User inherited from APIConnection

    # so that I might call Profile-related functions like this through composition


    def edit_profile(self):

        self.api_call()


    def remove_avatar(self):

        self.api_call()



# My endgoal is so the user can write stuff like:

user = User("username", "password")

user.profile.edit_profile()

user.profile.remove_avatar()

# which would only be possible if Profile could share the APIConnection object that User created

我是 OO 编程的新手,想不出一种干净的方法来做到这一点。


我希望创建的Profile实例User也可以访问继承的实例,APIConnection而不必重新创建它或做任何奇怪的事情。


FFIVE
浏览 94回答 1
1回答

萧十郎

是的,在静态语言中,您可以让您的Profiletake 引用 anAPIConnection并且编译器将强制执行该接口。使用 python,您可以进行单元测试,该测试实际通过APIConnection,然后User将捕获对方法的任何调用。事实上你可以这样做:class User(APIConnection):    def __init__(self, username, password):        super().__init__()        # do login stuff, get access token        # update inherited session with authorization headers        self.session.headers.update({"Access-Token": access_token})        self.profile = Profile(self, profile_data) # set up profile objectclass Profile:    def __init__(self, api, profile_data):        self.api = api    def edit_profile(self):        self.api.api_call()    def remove_avatar(self):        self.api.api_call()
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python