Default value in a function in Python [duplicate]

廉价感情. 提交于 2019-12-30 08:17:49

问题


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?


回答1:


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.




回答2:


This is a classic pitfall. See http://zephyrfalcon.org/labs/python_pitfalls.html, section 5: "Mutable default arguments"




回答3:


Always make functions like this then:

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

    self._data = data

Alternatively you could also use data = data or [], but that prevents the user from passing empty parameters ('', 0, False etc.).



来源:https://stackoverflow.com/questions/2313075/default-value-in-a-function-in-python

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