[python] inherit
An simple example presentation
1 #inherit 2 class Parent: 3 '''reprensent parent''' 4 def __init__(self, name, age): 5 self.name = name 6 self.age = age 7 print'initialized parent:{}'.format(self.name) 8 def show(self): 9 print 'name:{0},age:{1}'.format(self.name,self.age), 10 11 class Son(Parent):#inherit from parent 12 '''reprensent son''' 13 def __init__(self, name, age , height): 14 Parent.__init__(self, name, age) # invoking parent __init__() method, it must invoke manually 15 self.height = height# new attribute in child 16 print'initialized son:{}'.format(self.name) 17 def show(self): 18 Parent.show(self) 19 print 'height : {} '.format(self.height) 20 21 class Daughter(Parent):#inherit from parent 22 '''reprensent daughter''' 23 def __init__(self, name, age, weight): 24 Parent.__init__(self, name, age) # invoking parent __init__() method, it must invoke manually 25 self.weight = weight # new attribute in child 26 print'initialized daughter:{}'.format(self.name) 27 def show(self): 28 Parent.show(self) 29 print 'weight : {}'.format(self.weight) 30 31 s = Son('jack',20,175) 32 d = Daughter('tom',21,120) 33 for index in [s,d]: 34 index.show()
with above code executed, it should produce below result:
initialized parent:jack #the first thing that the parent __init__()method will be executed, and then child __init__() when instance of child class.
initialized son:jack
initialized parent:tom
initialized daughter:tom
name:jack,age:20 height : 175
name:tom,age:21 weight : 120