How do I use [] as a default value for a named function argument in python? [duplicate]

淺唱寂寞╮ 提交于 2019-12-22 10:50:20

问题


Possible Duplicate:
“Least Astonishment” in Python: The Mutable Default Argument

I have this code

class Test(object):
  def __init__(self, var1=[]):
    self._var1 = var1

t1 = Test()
t2 = Test()

t1._var1.append([1])

print t2._var1

and I get "[[1]]" as the result. So clearly t1._var1 and t2._var1 are addressing the same list. If I put

t3 = Test()
print t3._var1

then I get "[[1]]" as well. So var1=[] seems to permanently bind var1 to the some list. I tried copying the list,

def __init__(self, var1=copy([])):

but got the same result, so the expression for the named argument appears to be evaluated prior to init being called, and it just gave var1 a copy of the empty list which was then shared amongst the instances.

So how do I use [] as a default value for a named argument?


回答1:


You can't use [] directly if you want each object to have an empty list. I tend to use a work around:

def __init__(self, var1=None):
    if var1 is None:
        var1 = []
    ....

Naturally this won't work if var1 can be None, you would need to use a different object.



来源:https://stackoverflow.com/questions/13484107/how-do-i-use-as-a-default-value-for-a-named-function-argument-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!