• 抽象类


    抽象类

    抽象类:本质就是把多个类(People,Dog,Pig),抽取他们比较像的部分,最后得到一个父类(Animal),子类继承父类,让子类在继承的时候必须实现父类规定的一些方法(run、eat)。
    具体实现需要借助第三方模块abc。

    抽象类本质还是类,只能被继承,不能实例化

    好处是:做一种归一化,统一标准,降低使用者的使用复杂度。 

    class Animal:
        def run(self):
            pass
    
        def eat(self):
            pass
    
    
    class People(Animal):
        def run(self):
            print("people is walking")
    
        def eat(self):
            print("people is eating")
    
    
    class Pig(Animal):
        def run(self):
            print("pig is walking")
    
        def eat(self):
            print("pig is eating")
    
    
    class Dog(Animal):
        def run(self):
            print("dog is walking")
    
        def eat(self):
            print("dog is eating")
    
    
    people = People()
    pig = Pig()
    dog = Dog()
    
    people.eat()
    pig.eat()
    dog.eat()
    

     import abc,@abc.abstractclassmethod后,如果子类不定义@下面的属性,程序就会报错。

    import  abc
    class Animal(metaclass=abc.ABCMeta):     # 做成抽象类,只能被继承,不能实例化
        @abc.abstractclassmethod      # 只定义规范,不实现具体效果
        def run(self):
            pass
    
        @abc.abstractclassmethod  # 只定义规范,不实现具体效果
        def eat(self):
            pass
    
    
    class People(Animal):
        def run(self):
            print("people is walking")
    
    
    class Pig(Animal):
        def run(self):
            print("pig is walking")
    
        def eat(self):
            print("pig is eating")
    
    
    class Dog(Animal):
        def run(self):
            print("dog is walking")
    
        def eat(self):
            print("dog is eating")
    
    
    people = People()
    # pig = Pig()
    # dog = Dog()
    
    # people.eat()
    # pig.eat()
    # dog.eat()
    

     TypeError: Can't instantiate abstract class People with abstract methods eat

  • 相关阅读:
    阿里的GCIH技术
    java栈
    hotsport jvm后台线程包括哪些
    java运行时数据区
    java双亲委派
    获取类加载器方式
    用户自定义类加载器(java防止反编译)
    JSP-07-使用JavaBean封装数据
    JSP-06-使用JDBC操作数据库
    InstallShield 下载安装
  • 原文地址:https://www.cnblogs.com/fantsaymwq/p/9917180.html
Copyright © 2020-2023  润新知