See*_*Yre 6 inheritance super python-2.7
我正在尝试了解如何进行这项工作。我想使用类方法实例化父类。这段代码给了我一个错误:
class Base(object):
def __init__(self, x, y, z):
self.x = x
self.y = y
self.z = z
@classmethod
def class_method(cls, a, b, c):
return cls(a, b, c)
class Child(Base):
def __init__(self, x, y, z, p):
super(Child, self).class_method(x, y, z)
self.p = p
c = Child(1, 2, 3, 10)
Run Code Online (Sandbox Code Playgroud)
我收到以下错误:
TypeError: __init__() takes at least 5 arguments (4 given)
Run Code Online (Sandbox Code Playgroud)
我也知道原因。这是因为cls变量保存了Child类。因此,当cls(a, b, c)调用时,python 尝试Child使用 4 个参数初始化该类,self, a, b, c。但该类Child需要 5 个参数。我如何实现这个功能?我知道除非绝对必要,否则我们不应该使用工厂方法。假设有必要。
您实际上不应该@classmethod在这个特定实例中使用
@staticmethod更好的解决方案
正如您所注意到的,类Child被传递到Base.do方法中。
但如果你想总是使用类Base,只需像这样创建静态方法
class Base:
@staticmethod
def do(a, b, c):
return Base(a, b, c)
Run Code Online (Sandbox Code Playgroud)
using@staticmethod更好,因为在 classBase的do方法中,您希望始终使用同一个类而不是其他类
当重命名类时,这可能是一个小问题,但可以使用 IDLE(或几乎任何其他文本编辑器)的替换功能来处理(编辑 > 替换 (Ctrl + H))