假设您有class Foo
,其中包含4种方法和class FooDecorator
。从这4种方法中,FooDecorator
只需要装饰一种方法。
从pythonic / OO设计的角度来看,使用__getattr__
将请求转发到已修饰的实例是否可以?这基本上会删除deocrator类中的大量样板代码。
示例:
class Foo(object):
def method_1(self):
return some, stuff
def method_2(self):
return some, stuff
def method_3(self):
return some, stuff
def method_4(self):
return some, stuff
class FooClassicDecorator(object):
def __init__(self, foo_instance):
self._foo_instance = foo_instance
def method_1(self):
returned = self._foo_instance.method_1()
return decorate_result(returned)
def method_2(self):
return self._foo_instance.method_2()
def method_3(self):
return self._foo_instance.method_3()
def method_4(self):
return self._foo_instance.method_4()
class FooGetattrDecorator(ojbect):
def __init__(self, foo_instance):
self._foo_instance = foo_instance
def __getattr__(self, attr_name):
return getattr(self._foo_instance, attr_name)
def method_1(self):
returned = self._foo_instance.method_1()
return decorate_result(returned)
你觉得哪个更优雅? FooClassicDecorator
或FooGetattrDecorator
?
答案 0 :(得分:1)
我发现了另一个非常相似的问题。最高投票和接受的答案似乎与我的FooGetattrDecorator非常相似
Implementing the decorator pattern in Python
关闭此内容并标记为重复。