zoukankan      html  css  js  c++  java
  • Python----面向对象---抽象类

    一、什么是抽象类

    与java一样,python也有抽象类的概念但是同样需要借助模块实现,抽象类是一个特殊的类,它的特殊之处在于只能被继承,不能被实例化

    二、抽象类与普通类的不同

    抽象类中只能有抽象方法(没有实现功能),该类不能被实例化,只能被继承,且子类必须实现抽象方法。

    三、在python中利用abc模块实现抽象类,示例代码如下:

     1 import abc
     2 
     3 
     4 class Animal(metaclass=abc.ABCMeta):
     5     @abc.abstractmethod
     6     def run(self):
     7         pass
     8 
     9     @abc.abstractmethod
    10     def eat(self):
    11         pass
    12 
    13 
    14 class People(Animal):
    15     # def run(self):
    16     #     print('is running')
    17     #
    18     # def eat(self):
    19     #     print('is eating')
    20     pass
    21 
    22 
    23 class Pig(Animal):
    24     def run(self):
    25         print('is running')
    26 
    27     def eat(self):
    28         print('is eating')
    29 
    30 
    31 class Dog(Animal):
    32     def run(self):
    33         print('is running')
    34 
    35     def eat(self):
    36         print('is eating')
    37 
    38 
    39 peo1 = People()
    40 pig1 = Pig()
    41 dog1 = Dog()
    42 peo1.eat()
    43 pig1.eat()
    44 dog1.eat()
    45 
    46 结果为:
    47 Traceback (most recent call last):
    48   File "C:/Users/xudachen/PycharmProjects/Python全栈开发/第三模块/面向对象/14 抽象类.py", line 39, in <module>
    49     peo1 = People()
    50 TypeError: Can't instantiate abstract class People with abstract methods eat, run

    报错原因为子类没有是实现抽象类功能,

  • 相关阅读:
    jenkins持续集成
    对pm2对研究
    模板⽅法模式
    python configparser模块
    Python正则表达式
    Python读写文件之换行符
    Python字符串
    Python字典
    Python列表
    爬虫 urllib,requests,lxml,bs4 小结
  • 原文地址:https://www.cnblogs.com/xudachen/p/8608683.html
Copyright © 2011-2022 走看看