Skip to main content
 首页 » 编程设计

python之如何在for循环中从类中获取实例名称

2025年05月04日12tuyile006

我将某个类的多个实例添加到列表中。我遍历该列表检查一些条件。在这些条件下,我从列表中选择某些对象并将它们添加到新列表中。因为这些对象来自一个类,所以新列表的内容是该类对象的内存分配。我想得到实例的原始名​​称。

老实说,我不知道为什么会这样,而且我还没有找到解决这个问题的任何答案,也许我在某个地方犯了一个错误,或者我只是不知道。请张贴答案

class Node(): 
    def __init__(self, y, x): 
        self.y = y 
        self.x = x 
    def operation(self): 
        return x**2 
 
node1 = Node(2,2) 
node2 = Node(3,3) 
 
nodes = [node1, node2] 
 
for node in nodes: 
    good_nodes = [] 
    if ##CONDITIONS##: 
        ##select certain nodes## 
    else: 
        good_nodes.append(##selected_nodes##, for example : node1) 
 
print(good_nodes) 

返回的内容: [<__main__.Node object at 0x7fe608b27668>]

我要返回的内容(列表): [node1,node2,etc]

请您参考如下方法:

名称与值相关联。值不知道引用它的名称。这意味着您无法从值中获取变量名称。

如果你想打印出一些以有意义的方式标识节点的东西,那么你可以覆盖 __str__()。例如:

class Node: 
    # existing code 
    def __str__(self): 
        return '(' + str(self.x) + ', ' + str(self.y) + ')' 

如果想让每个节点都有名字,那就得自己加上:

class Node: 
    def __init__(self, y, x, name): 
        self.y = y 
        self.x = x 
        self.name = name 

要打印出来,您必须修改第一个示例中的 __str__() 函数。