python中变量转字符串_在python中如何将变量转换成字符串

你基本上是在问“我的代码如何发现一个对象的名称?”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,正如其他人在这里提到的那样。当您实际需要知道对象关联的名称时,这是最佳选择。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值