Py学习  »  Python

在python中用父类方法重写init

Ignacio • 5 年前 • 2007 次点击  

我想做如下事情(在Python3.7中):

class Animal:

    def __init__(self, name, legs):
        self.legs = legs
        print(name)

    @classmethod 
    def with_two_legs(cls, name):
        # extremely long code to generate name_full from name
        name_full = name
        return cls(name_full, 2)

class Human(Animal):

    def __init__(self):
        super().with_two_legs('Human')

john = Human()

基本上,我想覆盖 __init__ 具有父类的工厂类方法的子类的方法。但是,编写的代码不起作用,并引发:

TypeError: __init__() takes 1 positional argument but 3 were given

我想这意味着 super().with_two_legs('Human') 通行证 Human 作为 cls 变量。

1) 为什么这件事不能按书面上说的做?我以为 super() 将返回超类的代理实例,因此 cls公司 会是 Animal 正确的?

2) 即使是这样,我也不认为这段代码实现了我想要的,因为classmethod返回了 动物 ,但我只想初始化 和classmethod一样,有什么方法可以实现我想要的行为吗?

我希望这不是一个很明显的问题,我发现 documentation 超级() 有点困惑。

Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/52310
 
2007 次点击  
文章 [ 2 ]  |  最新文章 5 年前