使用super()的子类构造函数-获取未绑定方法__init __() [英] Child Class constructor using super() - getting unbound method __init__()
问题描述
我正在尝试为子类创建类方法构造函数,但无法正确初始化实例。
I'm trying to create classmethod constructors for a child class, but I cannot initialize the instance properly.
我在该网站上阅读了许多博客和答案,甚至完全尝试了其他人发布的内容,但仍无济于事。希望我缺少一些非常简单的东西。我正在尝试的基本示例:
I have read many blogs and answers on this site and even tried exactly what some other people have posted, still to no avail. Hopefully I'm missing something really simple. Basic example of what I'm trying:
class A(object):
def __init__(self, foo):
self.foo = foo
class B(A):
@classmethod
def make_new(cls):
super(B, cls).__init__('bar')
foobar = B.make_new()
我不断收到未绑定方法错误:
I keep getting unbound method error:
TypeError: unbound method __init__() must be called with B instance as first argument (got str instance instead)
推荐答案
__ init __
方法是常规实例方法,而不是类方法。它需要将要初始化的实例调用时已经创建。您当前的代码失败的方式与 A .__ init __( foo)
失败的方式完全相同(这不是 super $的错c $ c>)。
The __init__
method is a regular instance method, not a class method. It needs the instance it is going to initialize to already have been created when it is called. Your current code is failing in exactly the same way that A.__init__("foo")
would fail (it's not the fault of super
).
我怀疑您想致电 __ new __
而不是 __init __
。 __ new __
方法是负责创建实例的实际构造函数方法(通常将实际创建步骤委托给 object .__ new __
)。您也不需要使用 super
,因为您没有覆盖您继承的 __ new __
方法(从对象
,因为 A
也不会覆盖它)。
I suspect you wanted to be calling __new__
rather than __init__
. The __new__
method is the actual "constructor" method that is responsible for creating the instance (usually by delegating the actual creation step to object.__new__
). You don't need to use super
either, since you've not overridden the __new__
method that you inherited (from object
, since A
doesn't override it either).
但是您实际上也不需要这样做。您只需调用 cls
参数,即可通过 classmethod
。调用类是构造实例的常规方法:
But you don't actually need to do that either. You can just call the cls
argument your classmethod
been passed. Calling a class is the normal way to construct instances:
class B(A):
@classmethod
def make_new(cls):
return cls("bar") # note that you also need to `return` the instance you create!
如果class方法的目的是避免运行 B .__ init __
,则可能需要以下内容:
If the purpose of the class method is to avoid running B.__init__
, you might want something like:
class B(A):
@classmethod
def make_new(cls):
self = cls.__new__(cls)
super(B, self).__init__('bar')
return self
这篇关于使用super()的子类构造函数-获取未绑定方法__init __()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!