类的继承与派生

继承 inheritance / 派生 derived
什么继承/派生
  继承是指从已有的类中派生出新的类,新类具有原类的行为,并能扩展新的行为
  派生类就是从一个已有类中衍生成新类,在新类上可以添加新的属性和行为
作用:
  1.用继承派生机制,可以将一些共有功能加在基类中,实现代码的共享
  2.在不改变基类的代码的基础上改变原有的功能
名语:
  基类(base class) /超类(super class)/ 父类(father class)
  派生类(derived class) / 子类(child class)


单继承:
语法:
  class 类名(基类名):
    语句块
说明:
  单继承是指由一个基类衍生出新的类

class Human:
    def say(self, what):
        print("", what)

    def walk(self, distance):
        print("走了", distance, "公里")

class Student(Human):       #Student继承与Human类,因此具备Human类中的方法
    def study(self, subject):
        print("正在学习", subject)


h1 = Human()
h1.say("今天天气真好")
h1.walk(5)


s1 = Student()
s1.walk(4)
s1.say("感觉有点累")
s1.study("python")

输出结果:
tarena@tedu:~/zengsf/824$ python3 exercise824_2.py
说 今天天气真好
走了 5 公里
走了 4 公里
说 感觉有点累
正在学习 python

 

posted on 2018-08-24 22:38  zengsf  阅读(848)  评论(0编辑  收藏  举报

导航