【发布时间】:2011-06-11 11:44:21
【问题描述】:
我需要来自第三方模块 m 的类 X 的一些功能。我可以直接使用 m.X,但将来我可能需要用另一个类 n.Y 替换 m.X(例如,如果我发现更好的实现)。
我想避免在这种情况下更改其余代码。
现在,我希望 m.X 的完整接口,包括初始化,保持不变。我为 m.X 编写了一个包装器 W,如下所示:
class W(m.X):
def __init__(self, *args):
super().__init__(*args)
以后如果有需要,我打算把上面的改写为:
class W(n.Y):
def __init__(self, *args):
super().__init__(*args)
# override instance methods of n.Y that don't share the semantics with m.X
# for example, in case f1 is hard to replicate in n.Y:
# def f1(self, *args):
# print("this method is no longer available")
# raise MyDeprecatedMethod()
# for example, in case f2 needs to be recalculated
# def f2(self, *args):
# do the calculations required to keep W.f2 unchanged
我当前的 m.X 包装器是否可以接受?它有问题吗,或者 n.Y 的计划包装器有问题吗?
【问题讨论】:
-
对我来说看起来不错(至少,我是这样做的)
-
您真正需要多少包装?如果唯一的问题是保护其余代码免受潜在的命名更改影响,那么只需
W = m.X就足够了,不是吗?
标签: python design-patterns interface wrapper