Python面向对象之抽象类与抽象方法
C++和Java中面向对象中有抽象类或接口的说法,在python中没有abstract或interface这样的内置关键字。但是abc模块(Abstract Base Classes)实现了这些抽象类检查的功能,其中ABC是抽象基类。@abstractmethod表示这个方法是一个抽象方法,子类必须重写。关于抽象类与抽象方法的示例代码如下:
from abc import ABC, abstractmethod
class Shape(ABC):
@abstractmethod
def area(self):
pass
@abstractmethod
def perimeter(self):
pass
class Circle(Shape):
def __init__(self, radius):
self.rad = radius
def area(self):
return 3.14 * self.rad * self.rad
def perimeter(self):
return 6.28 * self.rad
class Rectangle(Shape):
def __init__(self, width, height):
self.wid = width
self.he = height
def area(self):
return self.wid * self.he
def perimeter(self):
return 2*(self.wid + self.he)
circle = Circle(5)
print( circle.area() )
print( circle.perimeter() )
rectangle = Rectangle(4, 6)
print(rectangle.area())
print(rectangle.perimeter())