• (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方法。

      

     

     

  • 相关阅读:
    机器学习-正则化方法
    机器学习-回归算法
    机器学习算法一
    机器学习概览
    tensorflow机器学习初接触
    tensorflow决策树初接触
    tensorflow语法
    tensorflow第一个例子简单实用
    Hyperledger Fabric 1.0架构入门
    结合《XXXX需求征集系统》分析可用性和可修改性战术
  • 原文地址:https://www.cnblogs.com/Lival/p/6200821.html
Copyright © 2020-2023  润新知