是否有 Pythonic 泛型 "null dependency"?
Is there a Pythonic generic "null dependency"?
我经常发现自己处于 class 具有可选依赖项的情况。比如下面的notifier
.
class Example(object):
def __init__(self, notifier=None):
self._notifier = notifier or DummyNotifier()
def doTheBusiness(self):
doSomeWork()
self._notifier.notifyComplete()
由于notifier
是可选的,我有两个选择:
- 如果未提供
notifier
,请在其位置放置一个 DummyNotifier
(按照上面的示例),其中 DummyNotifier
是不执行任何操作的依赖项的实现
- 在
doTheBusiness
中,在调用任何东西之前检查 notifier
是否为 None
为了代码可读性,我更喜欢第一个选项,但它涉及到必须为每个依赖项(尽管很小)编写一个实现。
为了避免这种情况,我一直在考虑如下通用依赖项:
class GenericDependency(object):
def generic(self, *args, **kwargs):
pass
def __getattr__(self, _):
return self.generic
然后我可以调用任何方法:
gd = GenericDependency()
gd.notifyComplete()
gd.anythingElse("also", "works", "with", any="arguments")
(这显然只适用于操作 - 不适用于需要 return 值的函数。)
我的问题 - (1) 这是 Pythonic (2) 有没有更好的方法?
我会说 1) 是一个有效的解决方案,也称为 Null Object Pattern。
我看到另一种可能的解决方案:
1) 移除依赖并在 Example
class 之外调用 notifier
,即在调用 doTheBusiness
之后
2) 也许使用 Obeserver Pattern?
我经常发现自己处于 class 具有可选依赖项的情况。比如下面的notifier
.
class Example(object):
def __init__(self, notifier=None):
self._notifier = notifier or DummyNotifier()
def doTheBusiness(self):
doSomeWork()
self._notifier.notifyComplete()
由于notifier
是可选的,我有两个选择:
- 如果未提供
notifier
,请在其位置放置一个DummyNotifier
(按照上面的示例),其中DummyNotifier
是不执行任何操作的依赖项的实现 - 在
doTheBusiness
中,在调用任何东西之前检查notifier
是否为 None
为了代码可读性,我更喜欢第一个选项,但它涉及到必须为每个依赖项(尽管很小)编写一个实现。
为了避免这种情况,我一直在考虑如下通用依赖项:
class GenericDependency(object):
def generic(self, *args, **kwargs):
pass
def __getattr__(self, _):
return self.generic
然后我可以调用任何方法:
gd = GenericDependency()
gd.notifyComplete()
gd.anythingElse("also", "works", "with", any="arguments")
(这显然只适用于操作 - 不适用于需要 return 值的函数。)
我的问题 - (1) 这是 Pythonic (2) 有没有更好的方法?
我会说 1) 是一个有效的解决方案,也称为 Null Object Pattern。
我看到另一种可能的解决方案:
1) 移除依赖并在 Example
class 之外调用 notifier
,即在调用 doTheBusiness
之后
2) 也许使用 Obeserver Pattern?