Kry*_*ski 4 python class-method superclass
假设我有一堂课
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
Run Code Online (Sandbox Code Playgroud)
现在我已经扩展了上面的每个类,每个类都有一个具体的类:
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
Run Code Online (Sandbox Code Playgroud)
现在让我说我打电话
SpaceShuttleGenerator.get_description()
Run Code Online (Sandbox Code Playgroud)
问题在于,AdvancedGenerator我希望在SimpleGenerator传递类的实例时调用该方法,具体而言SpaceShuttleGenerator.可以这样做吗?
注意:示例是简化的,因为我的具体示例涉及更多.让我们说我的目标不是连接字符串.
用途super():
@classmethod
def get_description(cls):
desc = super(AdvancedGenerator, cls).get_description()
return desc + ' Advanced(tm) ' + cls.adv_feature
Run Code Online (Sandbox Code Playgroud)
使用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)'
Run Code Online (Sandbox Code Playgroud)
和使用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)'
Run Code Online (Sandbox Code Playgroud)