我想在本地范围内将类的方法作为函数(装饰后)公开。例如,如果我有一个类和装饰:如何在Python中自动公开和装饰函数版本的方法?
def some_decorator(f):
...transform f...
return decorated_f
class C(object):
def __init__(self,x):
self.x = x
def f(self,y):
"Some doc string"
return self.x + y
def g(self,y,z):
"Some other doc string"
return self.x + y + z
,如果我不关心automizing的过程中,我可以在下面的代码添加到我的模块如下:
@some_decorator
def f(C_instance,x):
"Some doc string."
return C_instance.f(x)
@some_decorator
def g(C_instance,x,y):
"Some other doc string."
return C_instance.g(x,y)
的效果以下评估为真
c = C(0)
f(c,1) == c.f(1)
但我希望能够自动做到这一点。像这样的:
my_funs = expose_methods(MyClass)
for funname, fun in my_funs.iteritems():
locals()[funname] = some_decorator(fun)
foo = MyClass(data)
some_functionality(foo,*args) == foo.some_functionality(*args)
会做的伎俩(虽然它感觉有点错误这样声明局部变量)。我怎样才能做到这一点,使方法的所有相关属性正确转换为函数版本?我将不胜感激任何建议。
P.S.
我知道我可以装饰类实例的方法,但这并不是我所追求的。它更多的是(1)对函数版本语法的偏好(2)我的装饰器使函数映射超过对象的集合,并且花哨和优化的方式。通过装饰方法获取行为(2)需要我的集合类从它们包含的对象继承属性,这与对集合语义是正交的。
修改由'locals()'返回的字典是未定义的。我想知道你为什么在这里使用'locals()'而不是'globals()'。据我所知,这些功能应该是在模块的全局范围内。 – 2012-02-29 19:34:56