问题描述
假设我有一个带有未实现方法的基类,如下所示:
Suppose I have a base class with unimplemented methods as follows:
class Polygon():
def __init__(self):
pass
def perimeter(self):
pass
def area(self):
pass
现在,假设我的一位同事使用 Polygon 类创建一个子类,如下所示:
Now, let's say one of my colleagues uses the Polygon class to create a subclass as follows:
import math
class Circle(Polygon):
def __init__(self, radius):
self.radius = radius
def perimeter(self):
return 2 * math.pi * self.radius
(H/Sh)e 忘记实现 area() 方法.
(H/Sh)e has forgotten to implement the area() method.
如何强制子类实现父类的area()方法?
How can I force the subclass to implement the parent's area() method?
推荐答案
这可能是你的父类:
class Polygon():
def __init__(self):
raise NotImplementedError
def perimeter(self):
raise NotImplementedError
def area(self):
raise NotImplementedError
虽然问题只会在运行时被发现,但当子类的一个实例试图调用这些方法之一时.
although the problem will be spotted at runtime only, when one of the instances of the child classes tries to call one of these methods.
另一个版本是使用 abc.abstractmethod
.
a different version is to use
abc.abstractmethod
.
from abc import ABC, abstractmethod
import math
class Polygon(ABC):
@abstractmethod
def __init__(self):
pass
@abstractmethod
def perimeter(self):
pass
@abstractmethod
def area(self):
pass
class Circle(Polygon):
def __init__(self, radius):
self.radius = radius
def perimeter(self):
return 2 * math.pi * self.radius
# def area(self):
# return math.pi * self.radius**2
c = Circle(9.0)
# TypeError: Can't instantiate abstract class Circle
# with abstract methods area
如果没有实现所有方法,您将无法实例化
Circle
.
you will not be able to instantiate a
Circle
without it having all the methods implemented.
这是
python 3
语法;在 python 2
你需要
this is the
python 3
syntax; in python 2
you'd need to
class Polygon(object):
__metaclass__ = ABCMeta
还要注意,对于二进制特殊函数
__eq__(), __lt__(), __add__(), ...
最好返回 NotImplemented
而不是引发 NotImplementedError
.
这篇关于强制子类覆盖父类的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!