I have two single inheritance classes, intended as a simple tree implementation:
class tree:
def __init__(self, nodes = set()):
self.nodes = nodes
def addnode(self, node):
self.nodes.add(node)
class Node(tree):
def __init__(self, name = '1', data = None, children = set()):
self.data = data
self.children = children
self.name = name
super().addnode(self)
tree()
Node('1')
However, running this code returns an error:
self.nodes.add(node)
^^^^^^^^^^
AttributeError: 'Node' object has no attribute 'nodes'
I couldn't find any resources that answer this specific question. can someone help me?
class tree:
def __init__(self, nodes=None):
if nodes is None:
nodes = set()
self.nodes = nodes
def addnode(self, node):
self.nodes.add(node)
class Node(tree):
def __init__(self, name='1', data=None, children=None):
super().__init__()
if children is None:
children = set()
self.data = data
self.children = children
self.name = name
super().addnode(self)
tree()
Node('1')
You need to initialize the parent class to be able to use it.
for more information look at: What does 'super' do in Python? - difference between super().__init__() and explicit superclass __init__()