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
  • 相关阅读:
    jq ajax注册检查用户名
    jq ajax页面交互
    Digit Counting UVA – 1225
    Molar mass UVA – 1586
    P1571 眼红的Medusa
    A. Digits Sequence Dividing
    Codeforces Round #535 (Div. 3) a题
    Digit Generator UVA – 1583
    Good Bye 2018 B
    电梯 HDU – 1008
  • 原文地址:https://www.cnblogs.com/huizaia/p/9668087.html
Copyright © 2011-2022 走看看