问题描述
我注意到以下内容:
class c:
def __init __(self,data = []) :
self._data = data
a = c()
b = c()
a._data.append(1)
print b._data
[1]
这是正确的行为吗?
是的,这是正确的行为。
但是,从您的问题来看,这似乎不是您所期望的。 / p>
如果您希望它符合您的期望,请注意以下几点:
规则1.请勿使用可变对象作为默认值。
def anyFunction(arg = []):
不会创建新的列表对象。 arg
的默认列表对象将在所有位置共享。
类似地
def anyFunction(arg = {}):
不会创建新的字典对象。此默认字典将被共享。
class MyClass(object):
def __init __(self,arg = None) :
self.myList = []如果arg为None arg
提供默认参数值,它是一个新鲜的空列表对象。
I am noticing the following:
class c:
def __init__(self, data=[]):
self._data=data
a=c()
b=c()
a._data.append(1)
print b._data
[1]
Is this the correct behavior?
Yes, it's correct behavior.
However, from your question, it appears that it's not what you expected.
If you want it to match your expectations, be aware of the following:
Rule 1. Do not use mutable objects as default values.
def anyFunction( arg=[] ):
Will not create a fresh list object. The default list object for arg
will be shared all over the place.
Similarly
def anyFunction( arg={} ):
will not create a fresh dict object. This default dict will be shared.
class MyClass( object ):
def __init__( self, arg= None ):
self.myList= [] if arg is None else arg
That's a common way to provide a default argument value that is a fresh, empty list object.
这篇关于Python函数中的默认值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!