简单的python oo问题
看看这个简单的例子。我不太明白为什么 o1 打印“Hello Alex”两次。我认为因为默认的 self.a 总是重置为空列表。有人可以向我解释一下这里的理由是什么吗?太感谢了。
class A(object):
def __init__(self, a=[]):
self.a = a
o = A()
o.a.append('Hello')
o.a.append('Alex')
print ' '.join(o.a)
# >> prints Hello Alex
o1 = A()
o1.a.append('Hello')
o1.a.append('Alex')
print ' '.join(o1.a)
# >> prints Hello Alex Hello Alex
Have a look a this simple example. I don't quite understand why o1 prints "Hello Alex" twice. I would think that because of the default self.a is always reset to the empty list. Could someone explain to me what's the rationale here? Thank you so much.
class A(object):
def __init__(self, a=[]):
self.a = a
o = A()
o.a.append('Hello')
o.a.append('Alex')
print ' '.join(o.a)
# >> prints Hello Alex
o1 = A()
o1.a.append('Hello')
o1.a.append('Alex')
print ' '.join(o1.a)
# >> prints Hello Alex Hello Alex
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
阅读有关可变默认函数参数的陷阱:
http://www.ferg.org/projects/python_gotchas.html
简而言之,当你定义时
self.a 引用的列表默认只定义一次,在定义时,而不是运行时。因此,每次调用
oaappend
或o1.a.append
时,您都会修改同一个列表。解决此问题的典型方法是:
通过将
self.a=[]
移动到__init__
函数的主体中,在运行时创建一个新的空列表(每次调用 __init__ 时),而不是在定义时。Read this Pitfall about mutable default function arguments:
http://www.ferg.org/projects/python_gotchas.html
In short, when you define
The list referenced by self.a by default is defined only once, at definition-time, not run-time. So each time you call
o.a.append
oro1.a.append
, you are modifying the same list.The typical way to fix this is to say:
By moving
self.a=[]
into the body of the__init__
function, a new empty list is created at run-time (each time__init__
is called), not at definition-time.Python 中的默认参数,例如:
被评估一次并在每次调用中重复使用,因此当您修改 a 时,您会全局修改 a 。一个可能的解决方案是:
您可以在以下位置阅读有关此问题的更多信息: http:// www.ferg.org/projects/python_gotchas.html#contents_item_6
基本上,永远不要在参数的默认值上使用可变对象,例如列表或字典。
Default arguments in Python, like:
are evaluated once and re-used in every call, so when you modify a you modify a globally. A possible solution is to do:
You can read more about this issue on: http://www.ferg.org/projects/python_gotchas.html#contents_item_6
Basically, never use mutable objects, like lists or dictionaries on a default value for an argument.