zoukankan      html  css  js  c++  java
  • (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方法。

      

     

     

  • 相关阅读:
    day12——Python高阶函数及匿名函数
    day11——Python函数的一般形式、函数的参数
    day10——Python file操作
    day9——Python复习
    day8——Python if,while,for
    day7——Python的帮助
    day6——Python数据类型
    sqlserver执行sql文件命令(sqlcmd)
    数据库快照、游标、锁
    Linux 下根据进程名kill进程
  • 原文地址:https://www.cnblogs.com/Lival/p/6200821.html
Copyright © 2011-2022 走看看