0

In the code below the i have called the constructor of class A in class B but I need to pass self in the parameters. Why do we to pass self that is a reference to object B to the constructor of A? Using Python 3.7.3

class A:
    def __init__(self,a):
        self.a = a
    def get_a(self):
        print(self.a)
class B(A): 
    def __init__(self,a,b):
        A.__init__(self,a)
        self.b = b
    def get_b(self):
        print(self.a)
        print(self.b)

a = A(5)
b = B(50,60)
a.get_a()
b.get_a()
b.get_b()
martineau
  • 119,623
  • 25
  • 170
  • 301
xufor
  • 79
  • 2
  • 8
  • 1
    Because that's the method signature? – Blorgbeard Apr 26 '19 at 16:19
  • Note that the instance of B is also an instance of A - that's OOP. – Blorgbeard Apr 26 '19 at 16:20
  • 2
    You need an instance of class A to avoid passing self by yourself, if you want to call a method from parent class you should use super https://docs.python.org/3/library/functions.html#super – bboumend Apr 26 '19 at 16:22
  • `__init__()` is _not_ a constructor (like C++ classes have), it's a class instance initializer and needs to be able to refer to the instance in order to be able to set-up its state. – martineau Apr 26 '19 at 16:25

0 Answers0