Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

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?

share|improve this question
2  
You need to call the base class __init__ from the derived class. There are many previous questions on this issue. –  BrenBarn Oct 24 '13 at 19:19
    
possible duplicate of How to use 'super' in Python? –  shx2 Oct 24 '13 at 19:20
    
@shx2: That question is rather Python 2-specific in its answers. –  Martijn Pieters Oct 24 '13 at 19:31

1 Answer 1

up vote 2 down vote accepted

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.

share|improve this answer
1  
You should probably mention it won't work in Python 2. –  zero323 Oct 24 '13 at 19:27
    
@zero323: The OP is using print() functions; I stuck to Python 3 for that reason. –  Martijn Pieters Oct 24 '13 at 19:28
    
Sometimes I feel like the only one using print() and Python 2.x –  zero323 Oct 24 '13 at 19:46
    
@zero323: Don't, unless you use from __future__ import print_function. –  Martijn Pieters Oct 24 '13 at 19:48

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.