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

时间:2020-08-18 13:57:58

标签: python python-3.x oop inheritance

在我的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

我是面向对象编程的新手,无法想到一种干净的方法来实现此目的。

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

谢谢。

1 个答案:

答案 0 :(得分:0)

是的,在静态语言中,您可以使Profile引用一个APIConnection,编译器将强制执行该接口。

使用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 object

class 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()