我正在尝试编写一个类方法装饰器来修改其类的状态。我现在很难实现它。
附带问题:装饰师何时被召唤?它是在实例化类时加载还是在类读取时读取时加载?
我想做的是:
class ObjMeta(object):
methods = []
# This should be a decorator that magically updates the 'methods'
# attribute (or list) of this class that's being read by the proxying
# class below.
def method_wrapper(method):
@functools.wraps(method)
def wrapper(*args, **kwargs):
ObjMeta.methods.append(method.__name__)
return method(*args, **kwargs)
return wrapper
# Our methods
@method_wrapper
def method1(self, *args):
return args
@method_wrapper
def method2(self, *args):
return args
class Obj(object):
klass = None
def __init__(self, object_class=ObjMeta):
self.klass = object_class
self._set_methods(object_class)
# We dynamically load the method proxies that calls to our meta class
# that actually contains the methods. It's actually dependent to the
# meta class' methods attribute that contains a list of names of its
# existing methods. This is where I wanted it to be done automagically with
# the help of decorators
def _set_methods(self, object_class):
for method_name in object_class:
setattr(self, method_name, self._proxy_method(method_name))
# Proxies the method that's being called to our meta class
def _proxy_method(self, method_name):
def wrapper(*fargs, **fkwargs):
return getattr(self.klass(*fargs, **fkwargs), method_name)
return wrapper()
我认为在类中手动编写方法列表很难看,所以也许修饰者会解决这个问题。
这是一个开源项目,我正在使用端口underscore.js到python。我知道它说我应该使用itertools或其他东西。我只是为了热爱编程和学习而这样做。 BTW,项目托管here
谢谢!
答案 0 :(得分:1)
这里有一些问题。
调用方法本身时会调用内部包装器内的任何内容。基本上,您正在使用包含原始函数的函数替换该方法。因此,您的代码将在每次调用时将方法名称添加到列表中,这可能不是您想要的。相反,该附加应该在method_wrapper
级别,即在内部包装器之外。定义方法时调用此方法,该方法在第一次导入包含类的模块时发生。
第二件事是错误的是你从来没有真正调用过该方法 - 你只需返回它。您应该使用提供的参数return method
返回调用方法的值,而不是return method(*args, **kwargs)
。