I am working on a grid-generator that takes x- and y-coordinates as input. When initiating, this node is stored using a @classmethod (storage is a set, see MWE) during which a unique index is provided. As part of __init__, there is a check if there is already a node with the same (x,y)-coordinates; if so, no new node should be created.
So far, so good. The problem arises when I want to return the previously defined node when the (x,y)-coordinates are already assigned to one. So when I initiate a node with previously defined (x,y)-coordinates, I want that previously defined node-object to be returned. As an example:
n1 = Node(x=0, y=0)
n2 = Node(x=0, y=0)
In this example, both n1 and n2 should contain exactly the same object, and not a copy with the same details. Thus, n1 == n2 should return True, as the objects are identical. This is necessary for further computations (left out for clarity reasons).
Below a MWE of my Node-class:
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
Stating that self becomes this previously defined node is not working; I have considered it. Thus as else-statement in the __init__:
...
else:
self = [n for n in self.__nodes if n.coordinates == (x, y)][0]
I have looked at the __hash__-method, but I am not familiar with it and I do not know if this is where the solution to my problem lies.
I am using Python 3.7. Thank you very much for any help; really appreciated!