Python 2.7 Python继承:将arg与kwarg混淆
如果我运行以下代码:Python 2.7 Python继承:将arg与kwarg混淆,python-2.7,inheritance,Python 2.7,Inheritance,如果我运行以下代码: class A(object) : def __init__(self, x, y, z=3.0): self.x = x self.y = y self.z = z class B(A): def __init__(self, a, b, c="c", *args, **kwargs): super(B, self).__init__(*args, **kwargs) s
class A(object) :
def __init__(self, x, y, z=3.0):
self.x = x
self.y = y
self.z = z
class B(A):
def __init__(self, a, b, c="c", *args, **kwargs):
super(B, self).__init__(*args, **kwargs)
self.a = a
self.b = b
self.c = c
if __name__=="__main__":
thing = B("a", "b", 1, 2)
print thing.x # expect 1
print thing.y # expect 2
print thing.z # expect 3
print thing.a # expect a
print thing.b # expect b
print thing.c # expect c
相反,我得到:
Traceback (most recent call last):
File "H:/Python/Random Scripts/python_inheritance.py", line 23, in <module>
thing = B(1,2,"a","b")
File "H:/Python/Random Scripts/python_inheritance.py", line 15, in __init__
super(B, self).__init__(*args, **kwargs)
TypeError: __init__() takes at least 3 arguments (2 given)
但从各个方面看,这似乎都很可怕。下面是代码中的两行代码,它们对齐显示为每个名称分配了哪个值:
def __init__(self, a, b, c="c", *args, **kwargs):
thing = B("a", "b", 1, 2)
如您所见,1
被分配给c
,在变量args
列表中只留下一个参数。问题是,在你假设的方式中,没有两个“类”的参数:虽然你称c
为“夸格参数”,但它实际上并不是这样定义的,就像a
一样。这两个问题都可以通过调用B(B=“B”,**some dict)
来解决,假设一些dict既有'a'
条目,又有'c'
条目。与args和kwargs之间的定义二分法不同,这里只有具有指定默认值的参数,而没有指定默认值的参数
我想你是对的,kwargs.pop()
是你最好的选择。我的代码中到处都是这样“可怕”的例子。将c=“c”
放在函数定义中并不会使c
成为一个只包含关键字的参数。在函数定义和函数调用中使用=无论什么
,都是完全、绝对、100%不相关的=函数定义中的which
仅表示如果未提供值,则参数值默认为which
。
def __init__(self, a, b, c="c", *args, **kwargs):
thing = B("a", "b", 1, 2)