Default value in a function in Python

This question already has an answer here:

  • “Least Astonishment” and the Mutable Default Argument 30 answers

  • 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.


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


    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.).

    链接地址: http://www.djcxy.com/p/28530.html

    上一篇: Python:Dictionary作为实例变量

    下一篇: Python中函数的默认值