Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
370 views
in Technique[技术] by (71.8m points)

introspection - How can I get the name of an object in Python?

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.

question from:https://stackoverflow.com/questions/1538342/how-can-i-get-the-name-of-an-object-in-python

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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])

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...