简体   繁体   中英

Python: Why does the object in my function return differing id()'s depending on how it is called?

I am experimenting with calling a function with different arguments. Now I know from the Python Docs (Python Tutorial 4.7.1. Defining Functions) - that a function accumulates the arguments passed to it on subsequent calls. Because of this after the first call I was expecting the id() of the list object in my function to remain constant, but it does not. Why are the id()'s different?

def f(a, L=[]):
    print(id(L))
    L.append(a)
    return L

>>> f(1)

2053668960840
[1]

>>> f(1)

2053668960840
[1, 1]

>>> f(1,[9])

2053668961032
[9, 1]

>>> f(1,[9])

2053669026888
[9, 1]

>>> f(1,[9])

2053668961032
[9, 1]

>>> f(1,[9])

2053669026888
[9, 1]

The default argument is bound to the function upon creation, it is always the same object in memory. That's why you are seeing the same id whenever you call your function without providing the second argument.

When you call your function with the second argument, in your case freshly created lists, the assignment L=<list called with> implicitly takes place inside the function body before any other code is executed. You see the id of your freshly created lists in this case.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM