1

I have some code to create a class hierarchy:

class LogicGate:
    def __init__(self, n):
        self.label = n
        self.output = None

class BinaryGate(LogicGate):
    def __init__(self, n):
        LogicGate.__init__(self, n)
        self.pinA = None
        self.pinB = None

class AndGate(BinaryGate):
    def __init__(self, n):
        super(AndGate, self).__init__(self, n)

But when I try to create an AndGate, an error occurs:

>>> AndGate('example')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 3, in __init__
TypeError: BinaryGate.__init__() takes 2 positional arguments but 3 were given

What is wrong with the code? Why does the error claim that 3 arguments are being given to BinaryGate.__init__()? How should I properly use super instead?

Karl Knechtel
  • 62,466
  • 11
  • 102
  • 153
lin Joe
  • 82
  • 1
  • 9

3 Answers3

4

When using super, self is passed automatically.

Also, in Python3.3 and above, super does not even need to receive arguments to know from which class it is being called. You can simply do this.

super().__init__(n)

This greatly improves maintainability, so it would be the prefered approach.

Olivier Melançon
  • 21,584
  • 4
  • 41
  • 73
3

If you are using Python 3.3 and above, you should replace

LogicGate.__init__(self,n)

with

super().__init__(n) 

It is better to use this format when ever you want to call super class constructor.

Farshid
  • 31
  • 2
2

You don't need to pass self here:

super(AndGate,self).__init__(self,n)

It should be

super(AndGate,self).__init__(n)
0xc0de
  • 8,028
  • 5
  • 49
  • 75