[Python] Get variable to which an object is assigned from inside the object?

Discussão em 'Python' iniciado por Stack, Fevereiro 9, 2025.

  1. Stack

    Stack Membro Participativo

    In Python, I'd like to get the variable to which an object is being assigned to. Something like:

    class Parent(object):

    def __init__(self):
    print(???) # Print the variable to which the created instance of
    # Parent has been assigned to.

    p = Parent() # This should print 'p'.


    I have come up with this:

    import inspect


    class Parent(object):

    def __init__(self):
    print((inspect.stack()[-1].code_context[-1].split()[0]))


    p = Parent()


    which, if I understand correctly, literally looks at the outermost call and there takes the left string part, which happens to be the variable - but to me this looks weird. Is there a better way?

    Continue reading...

Compartilhe esta Página