python中的ABC(Abstract Base Class)
2022/6/12 1:22:45
本文主要是介绍python中的ABC(Abstract Base Class),对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
一般来讲,抽象类具有的特点有:
- 拥有抽象方法,且抽象类不能被实例化
- 抽象类的子类必须实现抽象方法后才能被实例化。
python本身不能支持我们实现一个抽象类,以下语句并无报错。
>>> class Person: ... def say_something(): ... pass ... >>> a = Person()
python用module的方法,提供给我们定义一个抽象类的方式。
from abc import ABC,abstractmethod class Person(ABC): @abstractmethod def say_something(self): pass class Student(Person): def say_something(self): print("i m a student") pass
值得注意的是,在抽象类中定义的抽象方法是可以有实现的,不过子类仍需再次实现。
from abc import ABC,abstractmethod class Person(ABC): @abstractmethod def say_something(self): print("i m a person") class Student(Person): def say_something(self): super().say_something() print("i m a student")
这篇关于python中的ABC(Abstract Base Class)的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-03-30开始python成长之路
- 2024-03-29python optparse
- 2024-03-29python map 函数
- 2024-03-20invalid format specifier python
- 2024-03-18pool.map python
- 2024-03-18threads in python
- 2024-03-14python Ai 应用开发基础训练,字符串,字典,文件
- 2024-03-13id3 algorithm python
- 2024-03-13sum array elements python
- 2024-03-12python colon equals