[英]call @classmethod from another @classmethod of another class
[英]How to call a parent class's @classmethod from an overridden @classmethod in Python?
假設我有一堂課
class SimpleGenerator(object):
@classmethod
def get_description(cls):
return cls.name
class AdvancedGenerator(SimpleGenerator):
@classmethod
def get_description(cls):
desc = SimpleGenerator.get_description() # this fails
return desc + ' Advanced(tm) ' + cls.adv_feature
現在我已經擴展了上面的每個類,每個類都有一個具體的類:
class StringGenerator(SimpleGenerator)
name = 'Generates strings'
def do_something():
pass
class SpaceShuttleGenerator(AdvancedGenerator)
name = 'Generates space shuttles'
adv_feature = ' - builds complicated components'
def do_something():
pass
現在讓我說我打電話
SpaceShuttleGenerator.get_description()
問題是在AdvancedGenerator
我想調用SimpleGenerator
的方法傳遞類的實例,特別是SpaceShuttleGenerator
。 可以這樣做嗎?
注意:示例是簡化的,因為我的具體示例涉及更多。 讓我們說我的目標不是連接字符串。
使用super()
:
@classmethod
def get_description(cls):
desc = super(AdvancedGenerator, cls).get_description()
return desc + ' Advanced(tm) ' + cls.adv_feature
使用SimpleGenerator.get_description()
和super(AdvancedGenerator, cls).get_description()
之間的區別是cls
將被設置為。 直接調用類時, cls
設置為SimpleGenerator
,使用super()
, cls
將引用AdvancedGenerator
。
比較你的代碼(調整為使用__name__
來說明差異):
>>> class SimpleGenerator(object):
... @classmethod
... def get_description(cls):
... return cls.__name__
...
>>> class AdvancedGenerator(SimpleGenerator):
... @classmethod
... def get_description(cls):
... desc = SimpleGenerator.get_description()
... return desc + ' Advanced(tm)'
...
>>> AdvancedGenerator.get_description()
'SimpleGenerator Advanced(tm)'
並使用super()
:
>>> class AdvancedGenerator(SimpleGenerator):
... @classmethod
... def get_description(cls):
... desc = super(AdvancedGenerator, cls).get_description()
... return desc + ' Advanced(tm)'
...
>>> AdvancedGenerator.get_description()
'AdvancedGenerator Advanced(tm)'
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.