强制子类覆盖父方法 [英] Force child class to override parent's methods
问题描述
假设我有一个带有未实现方法的基类,如下所示:
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 ABCMeta, abstractmethod
import math
class Polygon(metaclass=ABCMeta):
@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 2 * math.pi * self.radius
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
你需要
class Polygon(object):
__metaclass__ = ABCMeta
还注意那对于二进制特殊函数 __ eq __(),_ _ lt __(),__ add __(),...
最好是 返回NotImplemented
而不是提出 NotImplementedError
。
这篇关于强制子类覆盖父方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!