0

In Python3 I assumed that the creation of a class with a parent causes the parent class to be instantiated. This code shows it does not work like that.

class AClass:
    def __init__(self):
    print("make A")
    self.val = True
def f(self):
    return self.val

class BClass(AClass):
    def __init__(self):
        print("make B")
        self.val = False
    def g(self):
        return self.val

b = BClass()
print(b.f())
print(b.g())

The output is

make B
False
False

The output shows AClass.__init__(self) is not called and the function f uses the self value created in BClass. If an AClass instance existed then the g function would have returned True.

I'm learning Python and I find this behavior very counterintuitive. What I want is to have a self instance variable at every level in the inheritance hierarchy. Is this not normal in Python3? If there were self instances in the inheritance tree would a method name follow the regular inheritance rules? Does Python do something else to implement what I want?

M Wade
  • 177
  • 1
  • 11
  • You should first fix your indentation in the posted code... – user202729 Mar 28 '18 at 07:50
  • _"What I want is to have a self instance variable at every level in the inheritance hierarchy."_ What does that even mean? When you instantiate a class you get __one__ object, not one for each class in the hierarchy. – Aran-Fey Mar 28 '18 at 08:13

1 Answers1

0

In order to call the init function of the parent you want to use :

Super(self, BClass).__init__()

Basically calling the parent class of the current instance (Thus sending the type of the instance of the class, and the currently instantiated class - self).

Also I dont find this counter intuitive, you over-writed the init function of the parent.

Rohi
  • 814
  • 1
  • 9
  • 26