首页 > 技术文章 > 类的抽象

huizaia 2018-09-18 11:50 原文

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

 

推荐阅读