简体   繁体   English

具有相同名称的对象在python中引用了不同的id

[英]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行和第2行创建了两个名为div对象。

  1. How does python differentiate between the two div objects created under the same scope? python如何区分在相同作用域下创建的两个div对象?

  2. When id() is applied on both objects, two different addresses are shown for the similar named objects. id()应用于两个对象时,将为相似的命名对象显示两个不同的地址。 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. 在像C这样的传统语言中,不能在相同范围内创建两个具有相同名称的变量。 But, in python this rule does not seem to apply. 但是,在python中,此规则似乎不适用。

In languages like C you can rename a variable with different values. 在像C这样的语言中,您可以使用不同的值重命名变量。 That is how you update a value. 这就是您更新值的方式。 In C they must have the same type though because C is a statically typed language. 在C语言中,它们必须具有相同的类型,因为C是一种静态类型的语言。 Python on the other hand is dynamically typed which means it doesn't track types. 另一方面,Python是动态类型的,这意味着它不会跟踪类型。 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. 在程序中,有一个表,其中名称与值相关联,并且当您在相同范围内将div定义为新值时,它只是覆盖了该值,因为第二个div稍后出现。 You can no longer access the function div any longer after the new div value has been defined. 定义新的div值后,您将无法再访问函数div

In Python everything (basically) is an object, and it does allow the re-use of variable names. 在Python中,所有东西(基本上)都是一个对象,它确实允许重用变量名。

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 . 因此,我相信您所做的是将变量名div从指向函数的名称重新分配给指向函数smart_div的指针。

You should see that you are unable to access the old div function. 您应该看到您无法访问旧的div函数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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