赞
踩
在Python中,抽象类是一种特殊的类,不能直接实例化,而是被用作其他类的基类。它定义了一组方法的接口,但没有具体的实现。子类必须实现这些方法才能实例化。
要创建一个抽象类,您需要使用abc模块中的ABC(Abstract Base Class)类,并通过将metaclass设置为ABCMeta来指定它是一个抽象类。
下面是一个使用抽象类的简单示例:
- from abc import ABC, abstractmethod
-
- class Shape(ABC):
-
- @abstractmethod
- def area(self):
- pass
-
- @abstractmethod
- def perimeter(self):
- pass
-
- class Rectangle(Shape):
-
- def __init__(self, width, height):
- self.width = width
- self.height = height
-
- def area(self):
- return self.width * self.height
-
- def perimeter(self):
- return 2 * (self.width + self.height)
-
-
- rectangle = Rectangle(5, 10)
- print(rectangle.area()) # 输出:50
- print(rectangle.perimeter()) # 输出:30
![](https://csdnimg.cn/release/blogv2/dist/pc/img/newCodeMoreWhite.png)
在上面的示例中,Shape是一个抽象类,它定义了两个抽象方法area()和perimeter()。Rectangle是Shape的子类,它必须实现这两个抽象方法才能实例化。
抽象类在面向对象编程中非常有用ÿ
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。