我想在我的本地范围内将类的方法公开为函数(装饰后)。例如,如果我有一个类和装饰器:
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
如果我不关心自动化该过程,我可以将以下代码添加到我的模块中:
@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)
大意是以下评估为 True
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)
就可以了(尽管以这种方式声明局部变量感觉有点错误)。我怎样才能做到这一点,以便该方法的所有相关属性都能正确转换为函数版本?如果有任何建议,我将不胜感激。
附注
我知道我可以装饰类实例的方法,但这并不是我真正想要的。它更多的是关于(1)对函数版本语法的偏好(2)我的装饰器使函数以奇特和优化的方式映射到对象集合的事实。通过装饰方法获取行为 (2) 需要我的集合类从它们包含的对象继承属性,这与集合语义正交。
最佳答案
您知道可以直接使用未绑定(bind)的方法吗?
obj.foo(arg)
等价于 ObjClass.foo(obj, arg)
class MyClass(object):
def foo(self, arg):
...
obj = MyClass()
print obj.foo(3) == MyClass.foo(obj, 3) # True
另请参阅Class method differences in Python: bound, unbound and static和 documentation .
关于python - 如何在Python中自动公开和修饰方法的函数版本?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9505341/