简体   繁体   English

Python - 如何打印 Object 的变量名

[英]Python - How to print the variable name of an Object

Thanks for reading.谢谢阅读。 Preface, I don't mean how to make a print(objectA) make python output something other than the <__main__.A object at 0x00000273BC36A5C0> via the redefining the __str__ attribute.前言,我不是说如何通过重新定义__str__属性使print(objectA) make python output 除了<__main__.A object at 0x00000273BC36A5C0>以外的东西。

I will use the following example to try to explain what I'm doing.我将使用以下示例来尝试解释我在做什么。

class Point:
    '''
    Represents a point in 2D space
    attributes: x, y
    '''

    def __init__(self, x=0, y=0):

        allowed_types = {int, float}

        if type(x) not in allowed_types or type(y) not in allowed_types:
            raise TypeError('Coordinates must be numbers.')

        else:
            self.x = x
            self.y = y

    def __str__(self):
        return f' "the points name" has the points: ({self.x}, {self.y})'

    __repr__ = __str__

I would like the "the points name" to be replaced with whatever the variable name assigned to a specific object. So if I instantiated pointA=Point(1,0) , I would like to be able to print pointA has the points: (1,0)我希望将“点名称”替换为分配给特定 object 的任何变量名称。因此,如果我实例化pointA=Point(1,0) ,我希望能够打印pointA has the points: (1,0)

I can't seem to find anything like this online, just people having issues that are solved by redefining __str__ .我似乎无法在网上找到类似的东西,只有遇到问题的人可以通过重新定义__str__来解决。 I tried to solve this issue by adding a.name attribute, but that made this very unwieldy (especially since I want to make other object classes that inherit Point()).我试图通过添加 a.name 属性来解决这个问题,但这使它变得非常笨拙(特别是因为我想制作其他继承 Point() 的 object 类)。 I'm not entirely sure if this is possible from what I know about variable and object names in python, but after wrestling with it for a couple of days I'd figured I'd reach out for ideas.根据我对 python 中的变量和 object 名称的了解,我不确定这是否可行,但在与它搏斗了几天之后,我想我会寻求想法。

Note that an object may be referred to as multiple names.请注意,object 可能被称为多个名称。 It is also possible that there is no object name referring to the object.也有可能没有 object 名称引用 object。

Below is one approach that achieves your goal.以下是实现您的目标的一种方法。 It uses globals() , the dictionary that stores mappings from names to objects inside the global environment.它使用globals() ,字典存储从名称到全局环境中对象的映射。 Essentially, the __str__ method searches the object in the global listings (so it can be very slow if there are many objects) and keeps the name if matches.本质上, __str__方法在全局列表中搜索 object(因此如果有很多对象,它可能会非常慢)并在匹配时保留名称。 You could possibly use locals instead to narrow the search scope.您可以改用locals来缩小搜索范围 scope。

In the example, C is referring to the same object as A .在示例中, C指的是与A相同的 object。 So print(C) tells both A and C are the names.所以print(C)告诉AC都是名字。

class Point:
  def __init__(self, x=0, y=0):
    self.x = x
    self.y = y
    
  def __str__(self):
    results = []
    for name, obj in globals().items():
      if obj == self:
        results.append(f' "{name}" has the points: ({self.x}, {self.y})')
    return "; ".join(results)

A = Point()
B = Point()
print(A) 
#"A" has the points: (0, 0)
print(B)
# "B" has the points: (0, 0)

C = A
print(C)
# "A" has the points: (0, 0);  "C" has the points: (0, 0)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM