我有类似的问题,但是我不知道这个词是什么
cat = 5
dog = 3
fish = 7
animals= [cat, dog, fish]
for animal in animals:
# by animal name, I mean the variable name that's being used
print(animal_name + str(animal))
它应该打印出来
cat5
dog3
fish7
所以我想知道是否有实际的方法或函数可以用来检索用作字符串的变量名。
最佳答案
您基本上是在问“我的代码如何发现对象的名称?”
def animal_name(animal):
# here be dragons
return some_string
cat = 5
print(animal_name(cat)) # prints "cat"
A quote来自 Fredrik Lundh(在 comp.lang.python 上)特别在这里很合适。
The same way as you get the name of that cat you found on your porch: the cat (object) itself cannot tell you its name, and it doesn’t really care — so the only way to find out what it’s called is to ask all your neighbours (namespaces) if it’s their cat (object)…
….and don’t be surprised if you’ll find that it’s known by many names, or no name at all!
只是为了好玩,我尝试使用 sys
和 gc
模块实现 animal_name
,发现邻居也在调用你的对象亲切地称为“猫”,即字面上的整数 5,有几个名字:
>>> cat, dog, fish = 5, 3, 7
>>> animal_name(cat)
['n_sequence_fields', 'ST_GID', 'cat', 'SIGTRAP', 'n_fields', 'EIO']
>>> animal_name(dog)
['SIGQUIT', 'ST_NLINK', 'n_unnamed_fields', 'dog', '_abc_negative_cache_version', 'ESRCH']
>>> animal_name(fish)
['E2BIG', '__plen', 'fish', 'ST_ATIME', '__egginsert', '_abc_negative_cache_version', 'SIGBUS', 'S_IRWXO']
对于足够独特的对象,有时您可以获得一个唯一的名称:
>>> mantis_shrimp = 696969; animal_name(mantis_shrimp)
['mantis_shrimp']
所以,总结一下:
- 简短的回答是:你不能。
- 长答案是:好吧,实际上,您有时可以 - 至少在 CPython 实现中。 To see how
animal_name
is implemented in my example, look here . - 正确答案是:使用
dict
,正如其他人提到的那样。当您实际需要使用名称 <--> 对象关联时,这是最佳选择。
关于python - 如何在python中将变量转换为字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9121376/