簡體   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