当前位置: 代码网 > it编程>前端脚本>Python > python中抽象类的实现

python中抽象类的实现

2026年09月02日 Python 我要评论
抽象类是不能直接创建实例的类,用来规定子类必须实现哪些方法。python 用 abc 模块实现,核心是两个东西:abc:继承它,就表示这是抽象类@abstractmethod:标记「子类必须实现」的方

抽象类是不能直接创建实例的类,用来规定子类必须实现哪些方法

python 用 abc 模块实现,核心是两个东西:

  • abc:继承它,就表示这是抽象类
  • @abstractmethod:标记「子类必须实现」的方法
from abc import abc, abstractmethod

class animal(abc):  # 继承 abc,表示这是一个抽象类
    @abstractmethod
    def speak(self):
        """子类必须实现这个方法"""
        pass

# animal = animal()  # typeerror: 不能实例化抽象类

class dog(animal):
    def speak(self):  # 必须实现抽象方法
        print("woof!")

dog = dog()
dog.speak()  # woof!

定义抽象类

from abc import abc, abstractmethod

class shape(abc):
    @abstractmethod
    def area(self):
        """计算面积"""
        pass

    @abstractmethod
    def perimeter(self):
        """计算周长"""
        pass

    def describe(self):
        """普通方法,子类可直接使用"""
        print(f"这是一个图形,面积: {self.area()}, 周长: {self.perimeter()}")

要点:

  • 继承 abc → 抽象类
  • @abstractmethod 标记的方法 → 子类必须实现
  • 可以同时有普通方法(有默认实现)
  • 抽象类不能被实例化

抽象属性

方法之外,属性也可以要求子类必须提供:

from abc import abc, abstractmethod

class employee(abc):
    @property
    @abstractmethod
    def salary(self):
        """子类必须实现 salary 属性"""
        pass

class fulltimeemployee(employee):
    def __init__(self, monthly_salary):
        self._monthly_salary = monthly_salary

    @property
    def salary(self):
        return self._monthly_salary

emp = fulltimeemployee(10000)
print(emp.salary)  # 10000
  • @abstractmethod:标记这个方法/属性必须被子类实现
  • @property:让子类实现后可以用 emp.salary 而不是 emp.salary() 来访问,像属性一样使用

两者组合起来就是:强制子类提供一个"属性",且调用方式像属性而非方法

注意: @property 要写在 @abstractmethod 上面,顺序不能颠倒。

子类必须实现全部抽象方法

少实现一个,子类本身仍是抽象类,照样不能实例化:

class rectangle(shape):
    def __init__(self, width, height):
        self.width = width
        self.height = height

    def area(self):
        return self.width * self.height

    # 忘记实现 perimeter 方法

# rect = rectangle(3, 4)  # typeerror: 不能实例化抽象类 rectangle

到此这篇关于python中抽象类的实现的文章就介绍到这了,更多相关python 抽象类内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!

(0)

相关文章:

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论

验证码:
Copyright © 2017-2026  代码网 保留所有权利. 粤ICP备2024248653号
站长QQ:2386932994 | 联系邮箱:2386932994@qq.com