0

This question is very simple, and I expect the answer will also be very simple.

Is there a way that I can return the string corresponding to the name I have chosen to bind to an instance of an object? For example, if I have written the following line of code:

tesla = Car(fuel='electric')

I would like some function getname() that I can call roughly as follows:

[In] tesla.*getname*()

[Out] 'tesla'

getname need not be called as a method of the object, I am also happy to call it as:

[In] *getname*(tesla)

[Out] 'tesla'

I'm sure there must be some function that accomplishes this goal, but I have yet to find it. All I have found relating to the topic is the __name__ attribute of an object, but this seems to return the name of the class of the object (in this example, 'Car'), not the name bound to that object in the current environment.

martineau
  • 119,623
  • 25
  • 170
  • 301
  • 2
    No, since not all objects have a variable name (and they can have multiple). What would be the instance name of `foo(1,2,{})`? – Willem Van Onsem Dec 30 '17 at 22:28
  • 1
    So what should the name be when you use `foo = tesla`? Or put the object in a list? `cars = [Car(fuel='diesel'), Car(fuel='petrol')]`. – Martijn Pieters Dec 30 '17 at 22:28
  • 1
    Names are *just references*, Python has loads of references. Objects generally don't know nor should much care about what references there are. – Martijn Pieters Dec 30 '17 at 22:29
  • I think I understand the point you are all making. Names are 'one-way' associations. To get the name bound to an object instance I would have to search through the space of all names, checking in each case whether the associated name was equal to the object, which is an unnatural operation (in a sense, it's meta-logical). – Leland Reardon Dec 30 '17 at 22:31

0 Answers0