假设我有这样的代码:
x = 0
y = 1
z = 2
my_list = [x, y, z]
for item in my_list:
print("handling object ", name(item)) # <--- what would go instead of `name`?
如何在 Python 中获取每个对象的 name?也就是说:我可以在这段代码中写什么来代替name
,这样循环会显示handling object x
,然后是handling object y
和 处理对象 z
?
在我的实际代码中,我有一个函数字典 that I will call later after looking them up用户输入:
def fun1():
pass
def fun2():
pass
def fun3():
pass
fun_dict = {'fun1': fun1,
'fun2': fun2,
'fun3': fun3}
# suppose that we get the name 'fun3' from the user
fun_dict['fun3']()
我怎样才能自动创建 fun_dict
,而不用写两次函数的名称?我希望能够写出类似的东西
fun_list = [fun1, fun2, fun3] # and I'll add more as the need arises
fun_dict = {}
for t in fun_list:
fun_dict[name(t)] = t
避免重复名称。
最佳答案
对象在 Python 中不一定有名称,因此无法获取名称。
当你创建一个变量时,像上面的 x, y, z
那么这些名字只是作为对象的“指针”或“引用”。对象本身不知道您为它使用的名称,并且您无法轻松(如果有的话)获取对该对象的所有引用的名称。
但是,对象具有 __name__
的情况并不少见。属性。函数确实有一个 __name__
(除非它们是 lambdas ),所以我们可以通过例如构建 fun_dict
fun_dict = {t.__name__: t for t in fun_list)
关于python - 如何获取对象的名称?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1538342/