python 抽象类

这是一个正常类

python 复制代码
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
class A:
    def f(self):
        pass


class B(A):
    def g(self):
        print("g")


if __name__ == "__main__":
    a = A()
    b = B()
    b.g()  # g
    b.f()

抽象类(C++中含有纯虚函数的类,)

让A继承ABC,然后给f标上@abstractmethod,A就是一个抽象类了

必须要实现f才能实例化

python 复制代码
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
from abc import ABC, abstractmethod


class A(ABC):
    @abstractmethod
    def f(self):
        pass


class B(A):
    def f(self):
        print("f")

    def g(self):
        print("g")


class C(A):
    pass


if __name__ == "__main__":
    # a = A()
    b = B()
    b.g()  # g
    b.f()  # f
    c = C()  # TypeError: Can't instantiate abstract class C with abstract methods f
相关推荐
倔强青铜三15 小时前
苦练Python第46天:文件写入与上下文管理器
人工智能·python·面试
用户25191624271119 小时前
Python之语言特点
python
刘立军19 小时前
使用pyHugeGraph查询HugeGraph图数据
python·graphql
数据智能老司机1 天前
精通 Python 设计模式——创建型设计模式
python·设计模式·架构
数据智能老司机1 天前
精通 Python 设计模式——SOLID 原则
python·设计模式·架构
c8i1 天前
django中的FBV 和 CBV
python·django
c8i1 天前
python中的闭包和装饰器
python
这里有鱼汤1 天前
小白必看:QMT里的miniQMT入门教程
后端·python
TF男孩2 天前
ARQ:一款低成本的消息队列,实现每秒万级吞吐
后端·python·消息队列
该用户已不存在2 天前
Mojo vs Python vs Rust: 2025年搞AI,该学哪个?
后端·python·rust