gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-30 02:12:30 25 4
gpt4 key购买 nike

假设我有一个类

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会引用高级生成器

比较您的代码(调整为使用 __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)'

关于python - 如何从 Python 中重写的@classmethod 调用父类的@classmethod?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15291302/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com