11

假设我有一堂课

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. 这可以做到吗?

注意:该示例已简化,因为我的具体示例涉及更多。假设我的目标不是连接字符串。

4

1 回答 1

12

使用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)'
于 2013-03-08T10:04:52.497 回答