Reputation: 4510
I am using python 2.6
class Father(object):
def __init__(self, *args, **kwargs):
self.is_rich = 'yes'
self.single = 'yes'
class Son(Father):
def __init__(self, *args, **kwargs):
self.has_job = 'yes'
son = Son()
print dir(son) --> Does not display Father class attributes is_rich & single?
Why?
Upvotes: 1
Views: 584
Reputation: 251116
You need to call base class's __init__
, as python only invokes the first __init__
method found in the class hierarchy the __init__
in Father
is never invoked. You can do that using super
or using Father.__init__
as shown in @mgilson's answer.
class Son(Father):
def __init__(self, *args, **kwargs):
super(Son, self).__init__(*args, **kwargs)
self.has_job = 'yes'
Demo:
>>> s = Son()
>>> s.is_rich
'yes'
>>> s.single
'yes'
>>> s.has_job
'yes'
Upvotes: 2
Reputation: 17510
Looks like you didn't have your child chain the initialization up towards its parent.
Perhaps reading this will help: Why aren't Python's superclass __init__ methods automatically invoked?
Upvotes: 2
Reputation: 310117
You didn't call Father.__init__
. You need to do so explicitly or use super
1,2:
class Son(Father):
def __init__(self, *args, **kwargs):
Father.__init__(self, *args, **kwargs)
self.has_job = 'yes'
1super considered Super!
2super considered harmful
Upvotes: 3