【发布时间】:2011-10-13 20:58:28
【问题描述】:
可能重复:
“Least Astonishment” in Python: The Mutable Default Argument
今天下午我正在编写一些代码,偶然发现了我的代码中的一个错误。我注意到我新创建的一个对象的默认值是从另一个对象继承的!例如:
class One(object):
def __init__(self, my_list=[]):
self.my_list = my_list
one1 = One()
print(one1.my_list)
[] # empty list, what you'd expect.
one1.my_list.append('hi')
print(one1.my_list)
['hi'] # list with the new value in it, what you'd expect.
one2 = One()
print(one2.my_list)
['hi'] # Hey! It saved the variable from the other One!
所以我知道这样做可以解决:
class One(object):
def __init__(self, my_list=None):
self.my_list = my_list if my_list is not None else []
我想知道的是……为什么?为什么 Python 类是结构化的,以便跨类的实例保存默认值?
提前致谢!
【问题讨论】:
-
奇怪,让我想起了 JavaScript 中的原型链
-
这是python函数的一个方面,而不是类。无论如何,this post 可以帮助您弄清楚为什么 Python 是这样设计的。
-
好像最近几天我不断看到这个问题的新版本......
-
Python 函数(无论是方法还是普通函数)本身就是对象。默认参数绑定到参数名称(如果调用提供显式值,则隐藏);它的可见性是函数体。除了方法是定义类的成员这一事实之外,在类级别根本没有发生任何事情。
标签: python