0

I have made a class to create a node and I would like to create a default name based on the amount of nodes created. I am able to print the amount of nodes existing, however when using an fstring to refer to the counter results in "N0".

Using Node.counter inside the fstring results in a NameError "Node is not defined".

Any ideas how to fix this default naming? e.g. 6th node's name = N6

class Node(): counter = 0

def __init__(self,x,y,z, name=f"N{counter}" ):
    self.x = x
    self.y = y
    self.y = y
    self.z = z
    self.name = name

    Node.counter += 1


nodes = []
for i in range(10):
    nodes.append(Node(1,2,3))

print(vars(nodes[5]))

print(Node.counter)

Results in:

{'x': 1, 'y': 2, 'z': 3, 'name': 'N0'}
10
Johan Tuls
  • 105
  • 7
  • You can't do it as part of the default argument value. Do it within `__init__`'s body. – deceze Sep 02 '20 at 07:15
  • Sometimes it's easier than you think. The following works fine, thanks! ` def __init__(self,x,y,z, name=None): self.x = x self.y = y self.y = y self.z = z self.name = Node.counter if name == None else name ` – Johan Tuls Sep 02 '20 at 07:27

0 Answers0