小编Ign*_*cio的帖子

Python 3 中默认的 ```__new__``` 是什么?

我相信我对应该做什么有某种理解__new__(创建一个类的实例,但不初始化它,这是 的工作__init__)。但是,我想了解 Python 3__new__默认实现的方法。

我还发现它cls是 的一个参数有点令人困惑__new__,但它__new__是一个静态方法而不是一个类方法(我从文档中得到了这个)......现在它如何作为它的第一个参数传递一个类型?

python class-constructors default-constructor python-3.x

3
推荐指数
1
解决办法
882
查看次数

在python中用父类方法覆盖__init__

我想做以下事情(在 Python 3.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()
Run Code Online (Sandbox Code Playgroud)

基本上,我想__init__用父类的工厂类方法覆盖子类的方法。然而,所写的代码不起作用,并引发:

TypeError: __init__() takes 1 positional argument but 3 were given
Run Code Online (Sandbox Code Playgroud)

我认为这意味着作为变量super().with_two_legs('Human')传递。Humancls

1)为什么这不像写的那样工作?我假设super()会返回超类的代理实例,所以clsAnimal对的吗?

2)即使是这种情况,我也不认为这段代码实现了我想要的,因为 classmethod 返回 的实例Animal,但我只想以Human与 classmethod 相同的方式进行初始化,有什么方法可以实现我的行为想?

我希望这不是一个很明显的问题,我发现文件super() …

python inheritance constructor class-method

1
推荐指数
1
解决办法
1594
查看次数