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

前端 未结 7 1515

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

    I was independently working on this and have the following. It's not as comprehensive as driax's answer, but efficiently covers the case described and doesn't rely on searching for the object's id in global variables or parsing source code...

    import sys
    import dis
    
    class MyObject:
        def __init__(self):
            # uses bytecode magic to find the name of the assigned variable
            f = sys._getframe(1) # get stack frame of caller (depth=1)
            # next op should be STORE_NAME (current op calls the constructor)
            opname = dis.opname[f.f_code.co_code[f.f_lasti+2]]
            if opname == 'STORE_NAME': # not all objects will be assigned a name
                # STORE_NAME argument is the name index
                namei = f.f_code.co_code[f.f_lasti+3]
                self.name = f.f_code.co_names[namei]
            else:
                self.name = None
    
    x = MyObject()
    
    x.name == 'x'
    

提交回复
热议问题