我正在尝试为子类创建类方法构造函数,但无法正确初始化实例。
我在这个网站上阅读了很多博客和答案,甚至尝试了其他人发布的内容,但仍然无济于事。希望我错过了一些非常简单的东西。我正在尝试的基本示例:
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()
我不断收到未绑定(bind)方法错误:
TypeError: unbound method __init__() must be called with B instance as first argument (got str instance instead)
最佳答案
__init__
方法是常规实例方法,而不是类方法。它需要要初始化的实例在调用时已经创建。您当前的代码失败的方式与 A.__init__("foo")
失败的方式完全相同(这不是 super
的错误)。
我怀疑您想调用 __new__
而不是 __init__
。 __new__
方法是负责创建实例的实际“构造函数”方法(通常通过将实际创建步骤委托(delegate)给 object.__new__
)。您也不需要使用 super
,因为您没有重写您继承的 __new__
方法(从 object
继承,因为 >A
也不会覆盖它)。
但实际上您也不需要这样做。您可以只调用您传递的 classmethod
参数。调用类是构造实例的正常方法:
class B(A):
@classmethod
def make_new(cls):
return cls("bar") # note that you also need to `return` the instance you create!
如果类方法的目的是避免运行 B.__init__
,您可能需要类似以下内容:
class B(A):
@classmethod
def make_new(cls):
self = cls.__new__(cls)
super(B, self).__init__('bar')
return self
关于python-2.7 - 使用 super() 的子类构造函数 - 获取未绑定(bind)方法 __init__(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45429815/