0

Possible Duplicate:
subclass __init__ overrides superclass’s

class A():
    z = 'z it is'
    def __init__(self):
        self.a = 'a it is'

class B(A):
    def __init__(self):
        self.b = 'b it is'

b = B()
print b.z # z it is 
print b.a # AttributeError: B instance has no attribute 'a'

b is Instance of B class which is inherited from A class. Does it not implies that I can access attributes of parent class?

Community
  • 1
  • 1
Aamir Rind
  • 38,793
  • 23
  • 126
  • 164

2 Answers2

5

You need to explicitly call the superclass __init__. It is not automatically called.

BrenBarn
  • 242,874
  • 37
  • 412
  • 384
  • why explicitly? Is it for security purpose like accidentally changing the attrs e.g. concept of global vars – Aamir Rind Dec 24 '12 at 01:03
  • No, it's just to support nontrivial use cases (e.g. passing some but not all parameters on, or supplying something entirely else as parameter for the superclass constructor). An implicit approach would be full of ugly special rules and/or be limited to simple use cases. –  Dec 24 '12 at 01:07
0

The __init__ function in class B should be written like this:

class B(A):
    def __init__(self):
        A.__init__(self)
        self.b = "b it is"
prehistoricpenguin
  • 6,130
  • 3
  • 25
  • 42