python 中附加到对象的列表属性时出错

Error appending to objects' list attributes in python

我正在尝试制作一个模型,其中节点使用 OOP 相互连接。我希望每个节点都将其输入和连接的名称存储在列表中,并将这些列表作为属性。该代码似乎在“连接”功能之外完美运行。

它创建了所需的连接对象,但为目标节点和源节点创建了错误的属性。所需的属性是:

A.inputs = [],

A.outputs = [B]

B.inputs = [A]

B.outputs = [0]

但我得到的不是:

A.inputs = [A]

A.outputs = [B}

B.inputs = [A]

B.outputs = [B}

CONNECTIONS = []
NODES = []

class Zone: 
    def __init__(self, height, width):
        self.height = height
        self.width = width 

class Node:
    def __init__(self, name, initial_activation, activation_function = "linear", inputs  = [], outputs = [], location = (0,0)):
        global NODES
        self.name = name
        self.activation = initial_activation
        self.activation_function = activation_function
        self.inputs = inputs
        self.outputs = outputs
        self.location = location
        NODES.append(self)
    
    def __repr__(self):
        return(f"Node {self.name}")

class Connection: 
    def __init__(self, origin, destination):
        self.origin = origin.name
        self.destination = destination.name

    def __repr__(self):
        return(f"Connection from {self.origin} to {self.destination}")

def connect(origin, destination):
    new_connection = Connection(origin, destination)
    origin.outputs.append(destination.name) 
    destination.inputs.append(origin.name)
    global CONNECTIONS
    CONNECTIONS.append(new_connection)


A = Node("A",0)
B = Node("B", 0, location = (100,100))

A.__dict__  #  verify it is correct before hand
B.__dict__
test_connection = Connection(A,B)
test_connection.__dict__
connect(A,B)  #  create connection

A.__dict__  #  show erroneous result
B.__dict__
CONNECTIONS
CONNECTIONS[0].__dict__  #  verify connection object is correct

我曾尝试使用打印语句进行调试,但无济于事。我相信问题出在第 33 行和第 34 行,但我看不到这些行中的错误。

我看到节点 class 具有变量输入和输出的可变默认参数值。

在代码中,您不会为此参数传递值,因此 A.input 与 B.input 引用相同的列表。

print(id(A.inputs) == id(B.inputs))

将打印 True。

您需要摆脱可变的默认参数,f.e这样做:

class Node:
    def __init__(self, name, initial_activation, activation_function="linear",
                 inputs=None, outputs=None, location=(0, 0)):
        # Some code
        self.inputs = inputs or []
        self.outputs = outputs or []