Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I get the name of an object?

Is there any way to get the name of an object in Python? For instance:

my_list = [x, y, z] # x, y, z have been previously defined  for bla in my_list:     print "handling object ", name(bla) # <--- what would go instead of `name`?     # do something to bla 

Edit: Some context:

What I'm actually doing is creating a list of functions that I can specify by the command line.

I have:

def fun1:     pass def fun2     pass def fun3:     pass  fun_dict = {'fun1': fun1,             'fun2': fun2,             'fun3': fun3} 

I get the name of the function from the commandline and I want to call the relevant function:

func_name = parse_commandline()  fun_dict[func_name]() 

And the reason I want to have the name of the function is because I want to create fun_dict without writing the names of the functions twice, since that seems like a good way to create bugs. What I want to do is:

fun_list = [fun1, fun2, fun3] # and I'll add more as the need arises  fun_dict = {} [fun_dict[name(t) = t for t in fun_list] # <-- this is where I need the name function 

This way I only need to write the function names once.

like image 994
Nathan Fellman Avatar asked Oct 08 '09 14:10

Nathan Fellman


People also ask

What is a name of an object?

The Object name may be a common name or classification of an object in a textual or codified form. By using broader terms in a classification system, the object can be classified as belonging to a particular group or category of objects.

How do you print an object name in Python?

Print an Object in Python Using the __repr__() Method It, by default, returns the name of the object's class and the address of the object. When we print an object in Python using the print() function, the object's __str__() method is called.

How do you call an object name in Java?

The dot ( . ) is used to access the object's attributes and methods. To call a method in Java, write the method name followed by a set of parentheses (), followed by a semicolon ( ; ). A class must have a matching filename ( Main and Main.


1 Answers

Objects do not necessarily have names in Python, so you can't get the name.

It's not unusual for objects to have a __name__ attribute in those cases that they do have a name, but this is not a part of standard Python, and most built in types do not have one.

When you create a variable, like the x, y, z above then those names just act as "pointers" or "references" to the objects. The object itself does not know what name you are using for it, and you can not easily (if at all) get the names of all references to that object.

Update: However, functions do have a __name__ (unless they are lambdas) so, in that case you can do:

dict([(t.__name__, t) for t in fun_list]) 
like image 194
Lennart Regebro Avatar answered Sep 23 '22 21:09

Lennart Regebro