我正在尝试编写一个像@property 一样工作的装饰器,但遇到了一些问题。
class Dec(object):
def __init__(self, fn):
self._fn = fn
self._before = None
@property
def before(self)
return self._before
@before.setter
def before(self, fn):
self._before = fn
def __call__(self, *args, **kwargs):
self._before(*args, **kwargs)
self._fn(*args, **kwargs)
def withbefore(fn):
return Dec(fn)
它是一个简单的链接装饰器。@property/@.setter 语法正是我想要克隆的。
这有效:
@withbefore
def foo():
...
@foo.before
def beforefoo():
...
但是在课堂上它不会:
class Weee(object):
@withbefore
def do_stuff(self):
pass
@do_stuff.before
def before_do_stuff(self):
pass
它会引发导入错误。
TypeError: 'NoneType' object is not callable
我怎样才能正确模拟 @property/.{setter,getter,deleter} ?