pydata

Keep Looking, Don't Settle

python class (2): inheritance

inheritance in class

key words: resue code, parent/children class, higher class/super class/ sub class

you can have as many children classes you want inherit from the parent class

#比如三个class,士兵,老师,学生,有共性:姓名,性别,年龄;有个性:士兵有军衔,老师有课程,学生有成绩
#当然可以用三个不同的class来包含共性和个性,但是更方便的是把共性放到一个parent class里面,
#然后各个个性放到不同的children class里面
class Person(object):
 def __init__(self, name, age):
  self.name = name
  self.age = age
 def __str__(self):
  print "Person -"
  return "My name is %s. I am %s years old" %(self.name, self.age) 

class Military(Person):
 def __init__(self, name, age, rank):
  Person.__init__(self, name, age)    #call Person class method
  self.rank = rank
 def __str__(self):    #it will overwrites the parent __str__ method
  print "Military -"
  return Person.__str__(self) + "I am a %s" %(self.rank)

class Teacher(Person):
 def __init__(self, name, age, subject):
  Person.__init__(self, name, age)    #call Person class method
  self.subject = subject
 def __str__(self):    #it will overwrites the parent __str__ method
  print "Teacher -"
  return Person.__str__(self) + "I teach %s" %(self.subject)

class Student(Person):
 def __init__(self, name, age, loans):
  Person.__init__(self, name, age)    #call Person class method
  self.loans = loans

person = Person('Mike', 20)
print person
m1 = Military('Dan', 20, 'Soldier')
print m1
t1 = Teacher('Mike', 35, 'Math')
print t1
s1 = Student('Ted', 20, 10000)
print s1

reference: https://www.youtube.com/watch?v=QFNaBiHob50