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

  • 相关阅读:
    Vue中过度动画效果应用
    最小公倍数和最大公约数求解方法
    Vue实现双向绑定的原理以及响应式数据
    Hive SQL语法总结
    java安装配置
    Ubuntu vmware补丁
    centos6 安装tensorflow
    python hive
    python 连接 hive
    ubuntu下python通过cx_Oracle库访问oracle数据库
  • 原文地址:https://www.cnblogs.com/sch01ar/p/7784442.html
Copyright © 2011-2022 走看看