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
  • 相关阅读:
    CASE WHEN用法
    BOS消息对话框
    BOS自定义等待窗口
    自定义F7
    BOS接口开发
    BOS开发-增删改查
    金蝶BOS工作流
    金蝶KDTable常用代码
    BOS开发常用代码
    Jenkins2 入门到精通(学习资料)
  • 原文地址:https://www.cnblogs.com/huizaia/p/9668087.html
Copyright © 2011-2022 走看看