在我的 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而不必重新创建它或做任何奇怪的事情。
萧十郎
相关分类