对象可以检查分配给它的变量的名称吗? [英] Can an object inspect the name of the variable it's been assigned to?

查看:37
本文介绍了对象可以检查分配给它的变量的名称吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 Python 中,有没有办法让对象的实例看到它分配给的变量名称?以下面的例子:

In Python, is there a way for an instance of an object to see the variable name it's assigned to? Take the following for example:

class MyObject(object):
    pass

x = MyObject()

MyObject 是否有可能在任何时候看到它已被分配给变量名称 x?就像在 __init__ 方法中一样?

Is it possible for MyObject to see it's been assigned to a variable name x at any point? Like in it's __init__ method?

推荐答案

没有.对象和名称存在于不同的维度中.一个对象在其生命周期中可以有多个名称,并且无法确定哪一个可能是您想要的.即使在这里:

No. Objects and names live in separate dimensions. One object can have many names during its lifetime, and it's impossible to determine which one might be the one you want. Even in here:

class Foo(object):
    def __init__(self): pass

x = Foo()

两个名称表示同一个对象(self__init__ 运行时,x 在全局范围内).

two names denote the same object (self when __init__ runs, x in global scope).

这篇关于对象可以检查分配给它的变量的名称吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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