编程语言
首页 > 编程语言> > 如何从Python中重写的@classmethod调用父类的@classmethod?

如何从Python中重写的@classmethod调用父类的@classmethod?

作者:互联网

假设我有一堂课

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)'

标签:superclass,python,class-method
来源: https://codeday.me/bug/20190725/1535310.html