我很難想出一種好的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實例上,但我有點想知道是否有合理的方法來繼承。
這太棒了!我認爲我需要更好地圍繞描述符進行包裝,這確實是這樣。至於裝飾製造商:是的,這就是我最終做的。問題在於,我作爲參數傳遞的是函數;每個版本的裝飾器都有多個函數定義。因此,在頂層定義的構造函數方法定義並將它們附加在構造函數中時,感覺有點冒險,因爲邏輯上我所做的是非常多的繼承。 –