如何解决跨多个实例共享单个基础对象
在我的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
,而不必重新创建它或做任何奇怪的事情。
谢谢。
解决方法
是的,在静态语言中,您可以使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()
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。