函数返回原始变量后,如何在Python中打印原始变量的名称?

2024-06-01 00:51:10 发布

您现在位置:Python中文网/ 问答频道 /正文

我有enum并使用变量myEnum.SomeNameAmyEnum.SomeNameB等。当我从函数返回其中一个变量时,是否可以打印它们的名称(例如myEnum.SomeNameA),而不是它们返回的值


Tags: 函数名称enummyenumsomenameasomenameb
3条回答

要添加到@Jay's answer,一些概念

Python“变量”只是对值的引用。每个值都占用给定的内存位置(请参见id()

>>> id(1)
10052552

>>> sys.getrefcount(1)
569

从上面,您可能注意到值“1”存在于存储器位置10052552处。在这个解释器实例中,它被引用了569次

>>> MYVAR = 1
>>> sys.getrefcount(1)
570

现在,请注意,因为还有另一个名称绑定到此值,所以引用计数增加了1

基于这些事实,判断哪个变量名指向某个值是不现实的/不可能的

我认为解决您的问题的最佳方法是将映射和函数添加到枚举引用中,并返回到字符串名称

myEnum.get_name(myEnum.SomeNameA) 

如果您想要示例代码,请发表评论

简短回答:没有

详细回答:这是可能的一些丑陋的黑客使用回溯,检查等,但它通常不推荐用于生产代码。例如,请参见:

也许可以使用变通方法将值转换回名称/表示字符串。如果你发布更多的示例代码和详细信息,说明你想要这个做什么,也许我们可以提供更深入的帮助

没有唯一的或原始的变量名 http://www.amk.ca/quotations/python-quotes/page-8

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*?"

相关问题 更多 >