简体   繁体   中英

Objects having same name refer to different id in python

In the below code snippet, two objects named div are created at lines 1 and 2.

  1. How does python differentiate between the two div objects created under the same scope?

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

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.

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.

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