【发布时间】:2015-07-10 22:19:59
【问题描述】:
我有一个从其父类继承修饰属性的类。我想再添加一个装饰器(@thedecorator1("yyy")),但不会覆盖整个方法和现有的装饰器。 (decorator的顺序在某种程度上很重要,decorator1应该总是在property.setter和thedecorator2之间)
这在 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类不继承自对象 - 使其成为“旧样式类”。许多不错的类机制在旧式类中不起作用 - 描述符,它是属性成为一个的基础。您的“财产”声明在那里无效。
标签: python inheritance metaprogramming decorator python-decorators