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!
Fredrik Lundh, 3 Nov 2000, in answer to the question "How can I get the name of a variable from C++ when I have the PyObject*?"
要添加到@Jay's answer,一些概念
Python“变量”只是对值的引用。每个值都占用给定的内存位置(请参见
id()
)从上面,您可能注意到值“1”存在于存储器位置10052552处。在这个解释器实例中,它被引用了569次
现在,请注意,因为还有另一个名称绑定到此值,所以引用计数增加了1
基于这些事实,判断哪个变量名指向某个值是不现实的/不可能的
我认为解决您的问题的最佳方法是将映射和函数添加到枚举引用中,并返回到字符串名称
如果您想要示例代码,请发表评论
简短回答:没有
详细回答:这是可能的一些丑陋的黑客使用回溯,检查等,但它通常不推荐用于生产代码。例如,请参见:
也许可以使用变通方法将值转换回名称/表示字符串。如果你发布更多的示例代码和详细信息,说明你想要这个做什么,也许我们可以提供更深入的帮助
没有唯一的或原始的变量名 http://www.amk.ca/quotations/python-quotes/page-8
相关问题 更多 >
编程相关推荐