Python.接口类 抽象类 多态

时间:2025-04-04 07:31:51
from abc import ABCMeta,abstractmethod #从abc模块中导入ABCMeta这个元类 class GraphicRule(metaclass=ABCMeta): #接口类: @abstractmethod def area(self,length,width): pass @abstractmethod def perimeter(self,length,width): pass class Rectangle(GraphicRule): #子类继承了接口类后,才可以实现接口类中指定好的规范 def __init__(self,length,width): self.length = length self.width = width #对父类这个接口类中指定好的规范进行实现 def area(self,length,width): return length * width def perimeter(self,length,width): return (length+width)*2 r = Rectangle(2,3) r.area(2,3) from abc import ABCMeta,abstractmethod #从abc模块中导入ABCMeta这个元类 class GraphicRule(metaclass=ABCMeta): #接口类: @abstractmethod def area(self,length,width): pass @abstractmethod def perimeter(self,length,width): pass class Rectangle(GraphicRule): #子类继承了接口类后,才可以实现接口类中指定好的规范 def __init__(self,length,width): self.length = length self.width = width #对父类这个接口类中指定好的规范进行实现 def area(self,length,width): return length * width def perimeter(self,length,width): return (length+width)*2 r = Rectangle(2,3) r.area(2,3)