Section 7.20 Detailed Case: real Python subclass of abstract class
On section describes the Python abstract base class concepts, and describes the abstract base class implementation steps and grammar real subclass of this section in conjunction with a case in further detail.
First, the case described
in this section defines the abstract base class Shape pattern, area and perimeter requirements requested abstract method, then the derived two sub-classes rectangular and circular Rectangle Circle, constructor defined in the respective two sub-class, and seek to achieve a method of area and perimeter.
Second, the case of codes
1, into module abc ABC, abstractmethod
from abc import ABC, abstractmethod
2, the definition of the Shape abstract base class, and defines two abstract methods and getGirth getArea
class Shape(ABC):
@abstractmethod
def getArea():pass #定义获取面积的抽象方法
@abstractmethod
def getGirth():pass #定义获取周长的抽象方法
3, define and implement two subclasses Rectangle abstract base class and method getArea getGirth
class Rectangle(Shape):
def __init__(self,width,length): self.width,self.length = width,length
def getArea(self): return self.width*self.length
def getGirth():return(self.width+self.length)*2
4, define and implement a subclass of Circle getArea abstract base class method, but does not achieve another
class Circle(Shape):
def __init__(self,radius): self.radius = radius
def getArea(self): return 3.14*self.radius*self.radius
5, sub-class instantiation
rect = Rectangle(3,4)
cir = Circle(100)
Circle at this time because the two methods are not implemented and therefore will be reported TypeError wrong.
6, redefine and implement two subclasses Circle abstract base class and method getArea getGirth
class Circle(Shape):
def __init__(self,radius): self.radius = radius
def getArea(self): return 3.14*self.radius*self.radius
def getGirth(self):return 6.28*self.radius
7, re-instantiated instance round: cir = Circle (100), performs the normal case
8, acquisition area and perimeter two instances:
rect.getArea(),rect.getGirth() #矩形取面积和周长
cir.getArea(),cir.getGirth()#圆取面积和周长
Third, the case screenshots
This section provides a detailed combination of case definitions and methods of using real subclass of abstract class on a section of a demonstration, we can see real Python requires all subclasses of an abstract base class abstract method must be fully implemented.
Old ape Python (https://blog.csdn.net/LaoYuanPython) series of articles for the gradual introduction summary of the old ape learning Python learning experience, which helps no contact with Python programmers can easily enter Python world.
Welcome criticism, thank you attention!
Reproduced in: https: //www.cnblogs.com/LaoYuanPython/p/11087694.html