你基本上是在问“我的代码如何发现一个对象的名称?”def animal_name(animal):
# here be dragons
return some_string
cat = 5
print(animal_name(cat)) # prints "cat"
Fredrik Lundh(on comp.lang.python)的一个quote在这里特别适合。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,发现邻域还通过几个名称将您亲切地知道的对象称为“cat”,即文字整数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']
因此,总而言之:简单的回答是:你不能
正确答案是:使用dict,正如其他人在这里提到的那样。当您实际需要知道对象关联的名称时,这是最佳选择。