如何用多个参数重写Python类的构造函数?
比如说,我有一个类Foo,扩展类Bar。我想稍微凌驾于傅的建筑师之上。我甚至不想知道Bar的构造师是什么。有办法做到这一点吗 如果你不明白,我的意思是:如何用多个参数重写Python类的构造函数?,python,constructor,Python,Constructor,比如说,我有一个类Foo,扩展类Bar。我想稍微凌驾于傅的建筑师之上。我甚至不想知道Bar的构造师是什么。有办法做到这一点吗 如果你不明白,我的意思是: class Bar: def __init__ (self, arg1=None, arg2=None, ... argN=None): .... class Foo (Bar): #Here i just want add additional parameter to constructor, but don'
class Bar:
def __init__ (self, arg1=None, arg2=None, ... argN=None):
....
class Foo (Bar):
#Here i just want add additional parameter to constructor, but don't want to know anything about Bar's other parameters (arg1, arg2..., argN)
def __init__ (self, my_new_arg=None, ??? )
self.new_arg = my_new_arg
Bar.__init__(self, ??? )
有没有一种方法可以把一些简短而优雅的东西代替???在这个代码中?
(可能是args/kwargs的一些变体)
输出:
c 1
d 2
a 3
b 4
C1
d 2
a 3
b 4
@Acorn提出的
*args,**kwds
解决方案是一个良好的开端(尽管我对答案的*args
部分持异议)。Python的文章对这种方法进行了许多改进
*args
部分是不明智的,因为它不允许您在层次结构中插入新类,并且它阻止子类与可能具有不兼容位置参数的其他类使用多重继承。**kwds
方法工作得更好,因为它不强制执行调用链的特定顺序
另外请注意,您可以使用命名参数将当前方法的命名参数从其余关键字参数中分离并删除,然后再将其传递到链中:
class Bar(object):
def __init__(self, arg1=None, arg2=None, argN=None):
print arg1, arg2, argN
class Foo(Bar):
def __init__(self, my_new_arg=None, **kwds):
super(Foo, self).__init__(**kwds)
self.new_arg = my_new_arg
print my_new_arg
f = Foo(my_new_arg='x', arg2='y')
让每个方法去掉它需要的参数是很重要的,因为像这样的父方法根本不需要参数
最后一个注意事项是,如果要使用,请确保最顶级的类是新样式的(即,它继承自object或其他内置类型)。如果
Foo
对Bar
知之甚少,为什么它是从Bar
派生的?我的意思是,给定的技术可以节省时间,但是……请注意,\uuuuu init\uuuu
不是构造函数,而是初始值设定项,尽管它通常以相同的方式使用。否则\uuuu init\uuuu
将是一个@classmethod
。请注意,这个答案应该为Python3.x用户更新,它最终(尽管在这一点上,很久以前=)简化了超级调用:def\uuu init\uuuu(self,c,d,*args,**kwargs):super(*args,**kwargs)
。除非您处理多重继承,否则python已经知道它应该使用的唯一可能的超类。@Mike'Pomax'Kamermans您的意思可能是super()。\uuu init\uu(*args,**kwargs)
?
class Bar(object):
def __init__(self, arg1=None, arg2=None, argN=None):
print arg1, arg2, argN
class Foo(Bar):
def __init__(self, my_new_arg=None, **kwds):
super(Foo, self).__init__(**kwds)
self.new_arg = my_new_arg
print my_new_arg
f = Foo(my_new_arg='x', arg2='y')