如何在Python中获取对象的名称? [英] How can I get the name of an object in Python?

查看:532
本文介绍了如何在Python中获取对象的名称?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法在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

某些情况:

我实际上正在做的事情是创建可以在命令行中指定的功能列表.

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

我有:

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

我想拥有函数名称的原因是因为我想创建fun_dict而不写两次函数名称,因为这似乎是创建bug的好方法.我想做的是:

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.

推荐答案

对象不一定在python中具有名称,因此您无法获取名称. 在对象确实具有名称的情况下,它们具有__name__属性的情况并不罕见,但这不是标准python的一部分,并且大多数内置类型都没有一个.

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.

创建变量时,如上面的x,y,z,则这些名称仅充当对象的指针"或引用".该对象本身不知道您使用的名称是什么,并且您无法轻易(如果有的话)获取对该对象的所有引用的名称.

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.

更新:但是,函数确实具有__name__(除非它们是lambda),因此在这种情况下,您可以执行以下操作:

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

dict([(t.__name__, t) for t in fun_list])

这篇关于如何在Python中获取对象的名称?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆