问题
In the below code snippet, two objects named div
are created at lines 1 and 2.
How does python differentiate between the two
div
objects created under the same scope?When
id()
is applied on both objects, two different addresses are shown for the similar named objects. Why is this so?
def div(a,b):
return a/b
print(id(div)) # id = 199......1640 ################################ line 1
def smart_div(func):
def inner(a,b):
if a<b:
a,b=b,a
return func(a,b)
return inner
a = int(input("Enter 1st: "))
b = int(input("Enter 2nd: "))
div = smart_div(div)
print(id(div)) # id = 199......3224 ############################# line 2
print(div(a,b))
In legacy languages like C, one can't create two variables with the same name under same scope. But, in python this rule does not seem to apply.
回答1:
In languages like C you can rename a variable with different values. That is how you update a value. In C they must have the same type though because C is a statically typed language. Python on the other hand is dynamically typed which means it doesn't track types. In programs there is a table where names are associated with values and when you defined div
to a new value in the same scope it just wrote over that value because the second div
came later. You can no longer access the function div
any longer after the new div
value has been defined.
回答2:
In Python everything (basically) is an object, and it does allow the re-use of variable names.
So I believe what you have done is to re-assign the variable name div
from a name that pointed to a function, to a pointer to the function smart_div
.
You should see that you are unable to access the old div function.
来源:https://stackoverflow.com/questions/57465104/objects-having-same-name-refer-to-different-id-in-python