Use expressions as default values in function parameters
Python allows you to set a default value for a parameter of a function to make the parameter an optional parameter. Although this is a great feature of the language, it is a little troublesome when the default value is mutable. For example, consider the following Python function definition:
def foo(bar=[]):
# bar is an optional parameter, if not specified, the default value is[]... bar.append("baz")
# But this line is problematic, just look...
... return bar
A common mistake people make is that every time this function is called, if you don't assign a value to this optional parameter, it will always be assigned the value of this default expression. For example, in the above code, the programmer may think that calling the function foo() repeatedly (without passing the parameter bar to this function), this function will always return'baz', because we assume that every time foo() is called When (bar is not passed), the parameter bar will be set to [] (ie, an empty list).
So let's see what happens when we do this:
foo()["baz"]foo()["baz","baz"]foo()["baz","baz","baz"]
Ok? Why does this function always add our default value "baz" to an existing list every time foo() is called, instead of creating a new list every time?
The answer is the default value of a function parameter, which is assigned only once when the function is defined. In this way, only when the function foo() is defined for the first time, the default value of the parameter bar is initialized to its default value (that is, an empty list). When foo() is called (without the parameter bar), the list from the earliest initialization of bar will continue to be used.
Therefore, there can be the following solutions:
def foo(bar=None):...if bar is None:
# Or use if not bar:... bar =[]... bar.append("baz")...return bar
... foo()["baz"]foo()["baz"]foo()["baz"]
Content supplement:
So far, this article about Python Xiaobai should not use expressions indiscriminately. For more related Python expressions, please search ZaLou.Cn