我很难想到一种好的 python 并且符合 oop 原则的方法,因为我被教导要弄清楚如何在 python 中创建一系列相关的方法装饰器。
相互不一致的目标似乎是我希望能够访问装饰器属性和绑定装饰方法的实例的属性。这就是我的意思:
from functools import wraps
class AbstractDecorator(object):
"""
This seems like the more natural way, but won't work
because the instance to which the wrapped function
is attached will never be in scope.
"""
def __new__(cls,f,*args,**kwargs):
return wraps(f)(object.__new__(cls,*args,**kwargs))
def __init__(decorator_self, f):
decorator_self.f = f
decorator_self.punctuation = "..."
def __call__(decorator_self, *args, **kwargs):
decorator_self.very_important_prep()
return decorator_self.f(decorator_self, *args, **kwargs)
class SillyDecorator(AbstractDecorator):
def very_important_prep(decorator_self):
print "My apartment was infested with koalas%s"%(decorator_self.punctuation)
class UsefulObject(object):
def __init__(useful_object_self, noun):
useful_object_self.noun = noun
@SillyDecorator
def red(useful_object_self):
print "red %s"%(useful_object_self.noun)
if __name__ == "__main__":
u = UsefulObject("balloons")
u.red()
这当然会产生
My apartment was infested with koalas...
AttributeError: 'SillyDecorator' object has no attribute 'noun'
请注意,当然总有办法让它发挥作用。例如,一个有足够参数的工厂可以让我将方法附加到某些已创建的 SillyDecorator 实例,但我有点想知道是否有合理的方法通过继承来做到这一点。