• 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方法,并传入了重构父类属性后的参数

  • 相关阅读:
    测试sql语句性能,提高执行效率
    js积累
    如何提高AJAX客户端响应速度
    视频代码
    网页视频播放器收集
    WinForm软件开机自动启动详细方法
    JS时间格式化函数
    (转)CSS+DIV float 定位
    CSS+DIV 布局三种定位方式
    CSS+DIV布局初练—DIV元素必须成对出现?
  • 原文地址:https://www.cnblogs.com/sch01ar/p/7784442.html
Copyright © 2020-2023  润新知