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

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

Python如何在靜態方法中獲取對類的引用

Python如何在靜態方法中獲取對類的引用

郎朗坤 2023-06-06 10:29:09
如何在靜態方法中獲取對類的引用?我有以下代碼:class A:    def __init__(self, *args):        ...    @staticmethod    def load_from_file(file):        args = load_args_from_file(file)        return A(*args)class B(A):    ...b = B.load_from_file("file.txt")但是我想 B.load_from_file 返回 B 類型的對象,而不是 A。我知道如果 load_from_file 不是我可以做的靜態方法def load_from_file(self, file):        args = load_args_from_file(file)        return type(self)__init__(*args)
查看完整描述

1 回答

?
慕容708150

TA貢獻1831條經驗 獲得超4個贊

這就是classmethods 的用途;它們的相似之處staticmethod在于它們不依賴于實例信息,但它們通過將其作為第一個參數隱式提供來提供有關它被調用的類的信息。只需將您的備用構造函數更改為:


@classmethod                          # class, not static method

def load_from_file(cls, file):        # Receives reference to class it was invoked on

    args = load_args_from_file(file)

    return cls(*args)                 # Use reference to class to construct the result

當B.load_from_file被調用時,cls將是B,即使該方法是在 上定義的A,確保您構造正確的類。


一般來說,任何時候你發現自己編寫這樣的替代構造函數時,你總是希望classmethod能夠正確地啟用繼承。


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

添加回答

舉報

0/150
提交
取消
微信客服

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

幫助反饋 APP下載

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

公眾號

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