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
  • 相关阅读:
    setTimeout 理解
    Git 使用规范流程
    JavaScript异步编程 ( 一 )
    javaScript模块化一
    javascript 知识点坑
    javaScript闭包
    函数式编程
    JavaScript的68个技巧一
    MySql 隐式转换
    MySQL优化
  • 原文地址:https://www.cnblogs.com/huizaia/p/9668087.html
Copyright © 2011-2022 走看看