Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Having trouble with super()

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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__()

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading