有没有办法在启动新对象时返回先前定义的对象?
我正在研究一个以 x 和 y 坐标作为输入的网格生成器。启动时,此节点使用 a @classmethod(storage is a set,参见 MWE)存储,在此期间提供唯一索引。作为 的一部分__init__,检查是否已经存在具有相同 (x,y) 坐标的节点;如果是这样,则不应创建新节点。
到现在为止还挺好。当(x,y)坐标已分配给一个时,当我想返回先前定义的节点时,就会出现问题。因此,当我使用先前定义的 (x,y) 坐标启动节点时,我希望返回先前定义的节点对象。举个例子:
n1 = Node(x=0, y=0)
n2 = Node(x=0, y=0)
在这个例子中,n1和n2应该包含完全相同的对象,而不是具有相同细节的副本。因此,n1 == n2应该返回True,因为对象是相同的。这对于进一步的计算是必要的(为了清楚起见而省略)。
在我的Node类的 MWE 下面:
class Node:
__nodes = set() # Here, Node-objects are stored
__node_idx = None
def __init__(self, x, y):
# This is the check if the (x,y)-coordinates are already assigned to a node.
if (x, y) not in [n.coordinates for n in self.__nodes]:
self.x = x
self.y = y
self.set_idx(self)
self.store_node(self)
# Should here be something like an 'else'-statement?
@classmethod
def set_idx(cls, node):
"""Function to set unique index based on the number of nodes."""
# There is a procedure to determine this index, but that does not matter for the question.
node.__node_idx = idx
@classmethod
def store_node(cls, node):
cls.__nodes.add(node)
@property
def index(self):
return self.__node_idx
@property
def coordinates(self):
return self.x, self.y
声明self成为这个先前定义的节点不起作用;我已经考虑过了。因此作为else-statement 中的__init__:
...
else:
self = [n for n in self.__nodes if n.coordinates == (x, y)][0]
我看过__hash__-method,但我不熟悉它,我不知道这是不是我的问题的解决方案所在。
我正在使用 Python 3.7。非常感谢您的帮助;非常感谢!