Python方法:默认参数值为ONCE [英] Python methods: default parameter values are evaluated ONCE
问题描述
python 2.6.2( r262:71605,2009年4月14日,22:40:02)[$ v $ $ $ $ $ $ $ $ $ $ $ $ $ $%$ class a(object):
... def __init __(self,props = {}):
... self.props = props
...
>> ;> class b(a):
... def __init __(self,val = None):
... super(b,self).__ init __()
... self.props .update({'arg':val})
...
>>> class c(b):
... def __init __(self,val):
... super(c,self).__ init __(val)
...
>>> b_inst = b(2)
>>> b_inst.props
{'arg':2}
>>> c_inst = c(3)
>>> c_inst.props
{'arg':3}
>>> b_inst.props
{'arg':3}
>>>
在调试中,在第二次调用( c(3)
)你可以看到在 a
构造函数 self.props
已经等于 {'arg':2}
,之后调用 b
构造函数时,它将成为 {'arg': 3}
对于这两个对象!
同样,构造函数调用的顺序是:
a,b#for b(2)
c,a,b#for c(3)
如果您更改 self.props.update()
与 self.props = { arg:val}
在 b
构造函数中,一切都将正常,并将按预期方式执行
但我真的需要更新此属性,而不是替换
props
不应该有这样的默认值。这样做:
class a(object):
def __init __(self,props = None):
如果道具是无:
props = {}
self.props =道具
这是一个常见的python getcha。
I've found a strange issue with subclassing and dictionary updates in New-Style Classes:
Python 2.6.2 (r262:71605, Apr 14 2009, 22:40:02) [MSC v.1500 32 bit (Intel)] on
win32
>>> class a(object):
... def __init__(self, props={}):
... self.props = props
...
>>> class b(a):
... def __init__(self, val = None):
... super(b, self).__init__()
... self.props.update({'arg': val})
...
>>> class c(b):
... def __init__(self, val):
... super(c, self).__init__(val)
...
>>> b_inst = b(2)
>>> b_inst.props
{'arg': 2}
>>> c_inst = c(3)
>>> c_inst.props
{'arg': 3}
>>> b_inst.props
{'arg': 3}
>>>
In debug, in second call (c(3)
) you can see that within a
constructor self.props
is already equal to {'arg': 2}
, and when b
constructor is called after that, it becomes {'arg': 3}
for both objects!
also, the order of constructors calling is:
a, b # for b(2)
c, a, b # for c(3)
If you'll change self.props.update()
with self.props = {'arg': val}
in b
constructor, everything will be ok, and will act as expected
But I really need to update this property, not to replace
props
should not have a default value like that. Do this instead:
class a(object):
def __init__(self, props=None):
if props is None:
props = {}
self.props = props
This is a common python "gotcha".
这篇关于Python方法:默认参数值为ONCE的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!