Can an object inspect the name of the variable it's been assigned to?

前端 未结 7 1524

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


        
7条回答
  •  谎友^
    谎友^ (楼主)
    2020-11-29 11:54

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

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

提交回复
热议问题