具有相同名称的对象在python中引用了不同的id [英] Objects having same name refer to different id in python

查看:78
本文介绍了具有相同名称的对象在python中引用了不同的id的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在下面的代码片段中,在第1行和第2行创建了两个名为 div 的对象.

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

  1. python如何区分在相同作用域下创建的两个 div 对象?

在两个对象上都应用 id()时,将为相似的命名对象显示两个不同的地址.为什么会这样?

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)) 

在像C这样的传统语言中,不能在相同范围内创建两个具有相同名称的变量.但是,在python中,此规则似乎不适用.

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.

推荐答案

在C语言中,您可以使用不同的值重命名变量.这就是您更新值的方式.在C语言中,它们必须具有相同的类型,因为C是一种静态类型的语言.另一方面,Python是动态类型的,这意味着它不会跟踪类型.在程序中,有一个表,其中名称与值相关联,当您在相同范围内将 div 定义为新值时,它只是覆盖了该值,因为第二个 div 出现了之后.在定义了新的 div 值之后,您将无法再访问功能 div .

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.

这篇关于具有相同名称的对象在python中引用了不同的id的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆