zoukankan      html  css  js  c++  java
  • 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方法,并传入了重构父类属性后的参数

  • 相关阅读:
    微信小程序---app.json中设置背景色不生效解决办法
    给网站设置ICO图标
    ajax事件(五)
    ajax关于主流中的异类:应对Opera(四)
    dashboard
    tomcat 清理日志
    jQuery datatable
    php wampserver 80 端口无法开启的解决方法
    mysql 行列转换
    jQuery-2.1.4.min.js:4 Uncaught TypeError: Illegal invocation
  • 原文地址:https://www.cnblogs.com/sch01ar/p/7784442.html
Copyright © 2011-2022 走看看