search

Home  >  Q&A  >  body text

关于python 默认参数的疑问

python文档中关于默认参数是这样说的:

Default parameter values are evaluated when the function definition is executed. This means that the expression is evaluated once, when the function is defined, and that the same “pre-computed” value is used for each call.

因此,如下代码:

def function(data=[]):
    print id(data), data
    data.append(1)

for i in range(3):
    function()

输出结果为:

4462873272 []
4462873272 [1]
4462873272 [1, 1]

一切正像文档中说的那样,data只计算一次,之后的调用返回的是已经计算出来的值(因此,id(data)没有变化,每次append均针对同一个data)

但是我们带参数调用function时,即:

for i in range(3):
    function([])

输出结果为:

4462872984 []
4462872984 []
4462872984 []

data的值是符合预期的,但是三次调用function,id(data)的值竟然也一样,这个是为什么呢?带参数传递时,每次调用都应该是新建data的吧。

PHP中文网PHP中文网2805 days ago893

reply all(5)I'll reply

  • PHP中文网

    PHP中文网2017-04-17 13:39:41

    Read the documentation carefully: https://docs.python.org/2/library/functions.html#id.
    Because:

    Two objects with non-overlapping lifetimes may have the same id() value.

    The implementation of id in CPython is conceptually equivalent to the address of the object in memory. Then please look at this code:

    id([])
    # then it destory
    id([])
    # then its memory reused
    

    There are two different list objects before and after, but since the former object is destroyed after use, the latter list may reuse the same memory space, so the address returned by the id is the same.

    reply
    0
  • 天蓬老师

    天蓬老师2017-04-17 13:39:41

    LZ please pay attention to the difference between constants and variables. If you want a different id, you have to use list().

    reply
    0
  • 巴扎黑

    巴扎黑2017-04-17 13:39:41

    Although I don’t know if I have answered the question in the end, it would be good if this answer can help some students who are confused about the parameters.

    I just learned python a while ago. I saw a part about the default parameter list and wanted to share my understanding.

    When calling function f() three times in a row,

    The first time f() will find the default parameter data = []
    And its address in memory can be addressed through something like 'f.data'.
    Next, calling f() again will repeat the above operation. Because no new parameter is entered, the previous data will be found as the parameter list by default.

    def f(data = []):
        data.append("end")
        print data
    

    f()

    Before execution data = []
    After execution, the default parameters become data =['end']

    f()

    Repeat the last operation. The data here can be understood as a member variable of the function


    In addition, you can also call the f.defaults attribute to see what the default parameters of the current situation of function f are

    For example, after defining f,

     # 定义完f后的默认参数
    print f.__defaults__
    #>>([],)
    # f() 执行后的默认参数
    print f.__defaults__
    #>>(['end'],)
    

    So the default parameters are variable during the execution of f() several times.

    And if you call f([]), it will not affect the default parameters,

    print f.__defaults__
    f([])
    print f.__defaults__
    f([])
    print f.__defaults__
    

    You can try it if you are interested
    f(data = [] ) iterates :)

    You can refer to here. I think it is very clear about the parameters of functions in Python

    reply
    0
  • ringa_lee

    ringa_lee2017-04-17 13:39:41

    The question is like this...
    This is considered a relatively advanced content of Python..Beginners will basically encounter this problem


    Okay, let’s start the text

    The introspection of the function results in that your parameter is a attribute of the function type (although there is no way to access it with .).
    This means that when you define a function, your parameters have become part of the function object. Similar to:

    class cls():
        A = []
    
    a = cls()
    b = cls()
    a.A.append("a")
    print b.A
    

    You can find that the "a" just printed out..
    The same is true here for the function. The defined parameter attributes are shared
    But the above rules are only for variable data types, such as lists
    Because the immutable data type is not modified in the current memory block... but points to another memory block..


    Extended reading:

    Two python features:

    1. python dynamic type problem:

    Dynamic type means: your variable is just a something similar to a pointer. It’s just that he can point at random... what he points to is a type. This The type can be integer, string, class, etc.

    One of your variables can change the type it points to. For example: a = 1 in a points to an integer type. The value of this integer type is 1 (of course there are other components, such as There are also count and type declarations, etc.)
    But when you re-point to , for example: a = "hello world", what happens is that the variable a points to a string type, and the change to the integer type of 1 is count-1, the memory will not be reclaimed until count reaches 0.
    This is the legendary dynamic type

    2. Introspection of functions

    Functions are also types in python.
    For example, you

    def foo(a, b):
        pass
    

    Then a function type is generated and assigned to the variable foo..
    And everything in this type can be operated through the domain operator ..


    reply
    0
  • 伊谢尔伦

    伊谢尔伦2017-04-17 13:39:41

    Agree ls

    reply
    0
  • Cancelreply