zoukankan      html  css  js  c++  java
  • 类的抽象

    import abc
    
    class Animal(metaclass=abc.ABCMeta):  # 只能被继承,不能被实例化
    
        @abc.abstractmethod
        def run(self):
            print('-----')
    
        @abc.abstractmethod
        def eat(self):
            pass
    
    
    
    
    class Dog(Animal):
        def run(self):
            print('Dog is running')
    
        def eat(self):
            print('Dog is eating')
    
    
    class People(Animal):
        def run(self):
            print('People is running')
    
        def eat(self):
            print('People is eating')
    
    
    dog = Dog()
    peo = People()
    
    dog.run()
    peo.eat()
    
    
    输出:
    Dog is running
    People is eating

    当类被抽象时,只能被继承,不能被实例化,被实例化会报错。

    import abc
    
    
    class Animal(metaclass=abc.ABCMeta):  # 只能被继承,不能被实例化
    
        @abc.abstractmethod
        def run(self):
            print('-----')
    
        @abc.abstractmethod
        def eat(self):
            pass
        
        
    A = Animal()
    A.run()
    
    输出结果:
    Traceback (most recent call last):
      File "/Users/kouhui/Documents/python/MyFirstPython/面向对象/类的抽象.py", line 18, in <module>
        A = Animal()
    TypeError: Can't instantiate abstract class Animal with abstract methods eat, run
  • 相关阅读:
    linux bash shell之declare
    shell中的特殊符号
    工作常用shell集合
    sed实例收集
    vim粘贴代码时缩进混乱
    使用脚本实现killproc的功能
    zabbix 的安装
    Linux SSH 互信
    CeontOS7安装ansible
    xtrabackup 链接不上MySQL的问题
  • 原文地址:https://www.cnblogs.com/huizaia/p/9668087.html
Copyright © 2011-2022 走看看