First: you don't want to do this, there is no reason to do this, and if you think you need to do this, you're wrong.
Second: you can't do it in the __init__
method because the name reference test
referring to the new AnyClass
instance object hasn't been added to the memory space ("bound") yet. However, you could do it like this.
class AnyClass():
def echo_name(self):
{v:k for k,v in locals().items()}[self]
test = AnyClass()
test.echo_name()
This will return the first variable encountered in the locals()
dictionary that is assigned to the test
object. There is no guarantee for the order in which those variables will be returned.
To explain a bit further about why it won't work in the __init__
method, when you do this:
test = AnyClass()
A new instance of AnyClass
is constructed according to the instructions of the class definition (including the definitions of any parent or metaclass). This construction happens in phases, the last phase of which is executing the __init__
method. Prior to __init__
, other methods that will be executed, if they exist, are __new__
, and also the the __new__
, __init__
, and __call__
methods of the metaclass (if one exists).
So at the point in time the code in the body of the __init__
method is being executed, the object is still being constructed. Therefore there is, as of yet, nothing in the locals()
dictionary assigned to the name 'test'
. There is only a member called 'self'
. And, obviously, if you reverse-lookup the self
object in the locals()
dictionary looking for a registered name, the name you will get is the name 'self'
. Which... isn't useful.