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?