(Python)继承

面向对象的另一个特性是继承,继承可以更好的代码重用。

例如一个学校里面的成员有老师、学生。老师和学生都有共同的属性名字和年纪。但老师还有它自己的属性,如工资。学生也有它的属性,如成绩。

因此我们可以设计一个父类:SchoolPeople,两个子类:Teacher、Student。

代码如下:

SchoolPeople父类:

class SchoolPeople():
    def __init__(self,name,age):
        print "Init ShoolPeople"
        self.name=name
        self.age=age
    def tell(self):
        print "name is %s,age is %s" %(self.name,self.age)

Teacher子类:重写了父类的tell方法。

class Teacher(SchoolPeople):
    def __init__(self,name,age,salary):
        SchoolPeople.__init__(self,name,age)
        self.salary=salary
        print "Init teacher"
    def tell(self):
        print "salary is %d" %self.salary
        SchoolPeople.tell(self)

 Student子类:没有重写父类的方法

class Student(SchoolPeople):
   pass

调用:

t=Teacher("t1",35,10000)
t.tell()
print "
"
s=Student("s1",10,95)
s.tell()

结果:

Init ShoolPeople
Init teacher
salary is 10000
name is t1,age is 35


Init ShoolPeople
name is s1,age is 10

结果分析:虽然子类Student子类没有具体的实现代码,默认会调用父类的初始化函数和tell方法。

              子类Teacher重写了父类的tell方法,所以,他的实例会运行Techer类的tell方法。

  

 

 

原文地址:https://www.cnblogs.com/Lival/p/6200821.html