如何在靜態(tài)方法中獲取對類的引用?我有以下代碼: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 不是我可以做的靜態(tài)方法def load_from_file(self, file): args = load_args_from_file(file) return type(self)__init__(*args)
1 回答

慕容708150
TA貢獻1831條經(jīng)驗 獲得超4個贊
這就是classmethods 的用途;它們的相似之處staticmethod在于它們不依賴于實例信息,但它們通過將其作為第一個參數(shù)隱式提供來提供有關(guān)它被調(diào)用的類的信息。只需將您的備用構(gòu)造函數(shù)更改為:
@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被調(diào)用時,cls將是B,即使該方法是在 上定義的A,確保您構(gòu)造正確的類。
一般來說,任何時候你發(fā)現(xiàn)自己編寫這樣的替代構(gòu)造函數(shù)時,你總是希望classmethod能夠正確地啟用繼承。
添加回答
舉報
0/150
提交
取消