1

As you can see the code provided below, I was playing with OOP in python and discovered something i cannot wrap my head around. As far as i know we can call the constructor of a super class by using super() or the class name itself but here in lines #001 and #002 if I pass self in line #001 it gives me an error and if I do not pass self in #002 it again gives me an error. So why is there a difference between passing and not passing self when calling the constructor of super class by these two methods. And if there is a difference why do we even pass self in case of using the class name because self refers to the object of he child class, doesn't it?

class A:
    def __init__(self,a):
        self.a = a
        print('Printing self from constructor of A:')
        print(self)
        print('Printing self from constructor of B ends.\n')
    def get_a(self):
        print('-----------A-------------')
        print(self,'\n',self.get_a)
        print('-----------A-------------\n')
class B(A): 
    def __init__(self,a,b):
        #001 super().__init__(a)
        #002 A.__init__(self,a)
        print('Printing self from constructor of B:')
        print(self)
        print('Printing self from constructor of B ends.\n')
        self.b = b
    def get_b(self):
        #self.get_a works but get_a() doesn't
        print('-----------B-------------') 
        print(self,'\n',self.get_a,'\n')
        print(self,'\n',self.get_b)
        print('-----------B-------------\n')

a = A(5)
b = B(50,60)
a.get_a()
b.get_a()
b.get_b()

xufor
  • 79
  • 2
  • 8

0 Answers0