繁体   English   中英

Python - 如何打印 Object 的变量名

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

谢谢阅读。 前言,我不是说如何通过重新定义__str__属性使print(objectA) make python output 除了<__main__.A object at 0x00000273BC36A5C0>以外的东西。

我将使用以下示例来尝试解释我在做什么。

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__

我希望将“点名称”替换为分配给特定 object 的任何变量名称。因此,如果我实例化pointA=Point(1,0) ,我希望能够打印pointA has the points: (1,0)

我似乎无法在网上找到类似的东西,只有遇到问题的人可以通过重新定义__str__来解决。 我试图通过添加 a.name 属性来解决这个问题,但这使它变得非常笨拙(特别是因为我想制作其他继承 Point() 的 object 类)。 根据我对 python 中的变量和 object 名称的了解,我不确定这是否可行,但在与它搏斗了几天之后,我想我会寻求想法。

请注意,object 可能被称为多个名称。 也有可能没有 object 名称引用 object。

以下是实现您的目标的一种方法。 它使用globals() ,字典存储从名称到全局环境中对象的映射。 本质上, __str__方法在全局列表中搜索 object(因此如果有很多对象,它可能会非常慢)并在匹配时保留名称。 您可以改用locals来缩小搜索范围 scope。

在示例中, C指的是与A相同的 object。 所以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