【发布时间】:2016-10-16 06:48:18
【问题描述】:
有没有像我在这段代码中尝试过的那样在继承层次结构中管理 args 和 kwargs 的任何“好”方法。我的意思是不使用 kwargs 中的指定键或类似的东西获取值...
应该显示1 2 3 4:
class Parent(object):
def __init__(self, motherArg1, motherArg2=100):
self.motherArg1 = motherArg1
self.motherArg2 = motherArg2
def printParent(self):
print self.motherArg1
print self.motherArg2
class Child(Parent):
def __init__(self, childArg1, *args, childArg2=100, **kwargs): # Doesn't work here
super(Child, self).__init__(*args, **kwargs)
self.childArg1 = childArg1
self.childArg2 = childArg2
def printChild(self):
print self.childArg1
print self.childArg2
child = Child(1, 3, childArg2=2, motherArg2=4)
child.printChild()
child.printParent()
语法不好:预期为“);”在 *args 之后。
而def __init__(self, childArg1, childArg2=100, *args, **kwargs) 是正确的语法但不起作用。
- 当我尝试此语法和
child = Child(1, childArg2=2, 3, motherArg2=4)时,我得到 SyntaxError: non-keyword arg after keyword arg - 当我尝试
child = Child(1, 3, childArg2=2, motherArg2=4)时,我得到 TypeError: __init__() got multiple values for keyword argument 'childArg2'
【问题讨论】:
-
请edit 将格式正确的内容包含在问题本身中。在这种情况下,你会得到什么输出很明显,但是minimal reproducible example 是一个很好的习惯。
标签: python function inheritance arguments