我想包装各种对象的每个方法,除了__init__
使用装饰器。
class MyObject(object):
def method(self):
print "method called on %s" % str(self)
@property
def result(self):
return "Some derived property"
def my_decorator(func):
def _wrapped(*args, **kwargs):
print "Calling decorated function %s" % func
return func(*args, **kwargs)
return _wrapped
class WrappedObject(object):
def __init__(self, cls):
for attr, item in cls.__dict__.items():
if attr != '__init__' and (callable(item) or isinstance(item, property)):
setattr(cls, attr, my_decorator(item))
self._cls = cls
def __call__(self, *args, **kwargs):
return self._cls(*args, **kwargs)
inst = WrappedObject(MyObject)()
但是,属性实例结果的包装等价于:
@my_decorator
@property
def result(self):
return "Some derived property"
当期望的结果与此等效时:
@property
@my_decorator
def result(self):
return "Some derived property"
似乎属性对象的属性是只读的,防止在属性包装后修改函数。我对已经要求的黑客级别不太满意,无论如何我都不想深入研究属性对象。
我能看到的唯一其他解决方案是动态生成一个我希望避免的元类。我错过了一些明显的东西吗?