Python类(二)-类的继承

单继承

#-*- coding:utf-8 -*-
__author__ = "MuT6 Sch01aR"

class People:
    def __init__(self,name,age):
        self.name = name
        self.age = age

    def talk(self):
        print("%s is talking" %self.name)

    def eat(self):
        print("%s is eating" %self.name)

class Student(People):  #继承People
    def study(self):
        print("%s is studying" %self.name)

    def eat(self): #重构父类中的方法
        People.eat(self) #调用父类中被重构的方法
        print("%s doesn't like eating" %self.name)

class Teacher(People):
    def __init__(self,name,age,subject): #重构父类中的属性
        #super(Teacher,self).__init__(name, age) #新式类写法,建议用
        People.__init__(self, name, age)
        self.subject = subject

    def teach(self):
        print("%s is teaching %s" %(self.name,self.subject))

s1 = Student("Jack",14)
s1.talk()  #可以直接调用People里的方法
s1.study()
s1.eat()

t1 = Teacher("Jane",21,"Python")
t1.eat()
t1.teach()

 运行结果

Jack is talking   #调用父类的talk方法
Jack is studying   #调用本身的study方法
Jack is eating    #重构父类中的eat方法后又调用了父类的eat方法
Jack doesn't like eating   #调用了本身重构父类eat方法后的eat方法
Jane is eating      #调用父类的talk方法
Jane is teaching Python   #调用了本身的teach方法,并传入了重构父类属性后的参数

posted @ 2017-11-04 20:16  Sch01aR#  阅读(256)  评论(0编辑  收藏  举报