【发布时间】:2021-04-04 02:14:17
【问题描述】:
现在我正在创建一个代表闭区间的类。它的核心功能是提供一个intersect 方法。
class Interval:
def __init__(self, a, b):
# check a <= b otherwise swap
self.a = a
self.b = b
def intersect(self, other):
a = self.a if self.a > other.a else other.a
b = self.b if self.b < other.b else other.b
if b < a:
# return some value representing an empty interval, providing the intersect method
return Intervall(a,b)
应该可以表示特殊值,例如所有点 [-oo,oo] 或空集 {}。它仍然服务于intersect 方法。我目前的方法是创建一个新类,但这似乎有点乏味。
class EmptyInterval:
def intersect(self, other):
return self
假设那些特殊值的 intersect 方法优先,我会在 Intervall 类的方法之前添加:
class Intervall:
...
def intersect(self,other):
if not isinstance(self, other):
other.intersect(self)
...
澄清一下 - 以下内容应该是合法的:
a = Intervall(1,2)
b = Intervall(3,4)
c = a.intersect(b) # resulting in an empty interval
c.intersect(a) # resulting again in an empty interval
是否有一些优雅/更蟒蛇/不那么令人作呕的丑陋方式来实现这种行为?
首先我想到了继承,但这似乎很不合适,因为这些特殊值应该具有优先级;即我不知道如何通过继承来实现它。
【问题讨论】:
标签: python python-3.x oop inheritance