我很难想出一种好的python方法,并且符合oop原则,因为我已经被教会了解如何在python中创建一个相关的方法装饰器族。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实例上,但我有点想知道是否有合理的方法来继承。
这太棒了!我认为我需要更好地围绕描述符进行包装,这确实是这样。至于装饰制造商:是的,这就是我最终做的。问题在于,我作为参数传递的是函数;每个版本的装饰器都有多个函数定义。因此,在顶层定义的构造函数方法定义并将它们附加在构造函数中时,感觉有点冒险,因为逻辑上我所做的是非常多的继承。 –