亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

跨多個實例共享單個基礎對象

跨多個實例共享單個基礎對象

FFIVE 2023-06-06 14:47:29
在我的 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 stuffclass 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 objectclass 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而不必重新創建它或做任何奇怪的事情。
查看完整描述

1 回答

?
蕭十郎

TA貢獻1815條經驗 獲得超13個贊

是的,在靜態語言中,您可以讓您的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 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()


查看完整回答
反對 回復 2023-06-06
  • 1 回答
  • 0 關注
  • 126 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號