假设我有一个班级
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
。可以这样做吗?
注意:该示例已简化,因为我的具体示例更为复杂。让我们说我的目标不是连接字符串。
答案 0 :(得分:8)
使用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)'