我有一個繼承父級裝飾屬性的類。我想添加一個裝飾器(@thedecorator1("yyy")
),但不覆蓋整個方法和現有裝飾器。 (裝飾的順序很重要,在一定程度上,thedecorator1應該property.setter和thedecorator2之間總是)如何在Python中將裝飾器添加到繼承的方法而不復制整個方法?
這有可能在Python 3?
from functools import wraps
class thedecorator1:
def __init__ (self, idx):
self.idx = idx
def __call__ (self, func):
@wraps(func)
def wrapped(*args, **kwargs):
print("thedecorator1", self.idx, args)
return func(*args, **kwargs)
return wrapped
def thedecorator2(func):
def _thedecorator2(self, *args, **kwargs):
print("thedecorator2",args)
return func(self, *args, **kwargs)
return _thedecorator2
class SomeClass:
"""That's te base class"""
_some_property = None
@property
@thedecorator2
def someproperty(self):
return self._some_property
@someproperty.setter
@thedecorator1("xxx")
@thedecorator2
def someproperty(self, value):
self._some_property = value
class AnotherClass(SomeClass):
"""That's what works, but I need to copy everything everytime"""
_some_property = None
@property
@thedecorator2
def someproperty(self):
return self._some_property
@someproperty.setter
@thedecorator1("yyy")
@thedecorator1("xxx")
@thedecorator2
def someproperty(self, value):
self._someproperty = value
class YetAnotherClass(SomeClass):
"""That's what I think I need"""
dosomethingsmart(target = someproperty, decorator = thedecorator1("yyy"), after=someproperty.setter)
請注意,這是有效的Python3 - 但不會在Python2.x中工作,因爲您的'thedecorator1'類不會從對象繼承 - 使其成爲「舊式樣類」。許多很好的類機制在舊式類中不起作用 - 描述符,它們是屬性的基礎。你的「財產」聲明在那裏沒有效果。 – jsbueno