0

I faced with an inability of the inheritance of superclass attribute values. I have already called superclass constructor and now trying to check out the inherited values.

class base:
    def __init__(self, x):
        self.x = x
        print(self.x)

class derive(base):
    def __init__(self):
        print(self.x + 1)


print("base class: ")
b = base(1)                           <-- Creating superclass instance 
print("derive class: ")
d = derived()                         <-- Inheriting. Failure.

Why can't I do this? Should I pass the underlying object to the inheriting object explicitly in order to get x attribute?

Vitaly Isaev
  • 5,392
  • 6
  • 45
  • 64

1 Answers1

2

b and d are not related; b is entirely a separate instance of the base class.

If you want to invoke the overridden initializer (__init__), then use the super() proxy object to access it:

class derive(base):
    def __init__(self):
        super().__init__(1)
        print(self.x + 1)

Note that you still need to pass in an argument to the initializer of the parent class. In the above example, I pass in a constant value 1 for the x parameter of the parent initializer.

Note that I used Python 3 specific syntax here; super() without arguments won't work in Python 2, where you also need to use object as a parent for the base class to make it a new-style class.

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343