gpt4 book ai didi

python - Python中如何自动暴露和修饰方法的函数版本?

转载 作者:太空宇宙 更新时间:2023-11-04 01:36:15 25 4
gpt4 key购买 nike

我想在本地范围内将类的方法公开为函数(装饰后)。例如,如果我有一个类和装饰器:

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)

大意是下面的计算结果为真

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 staticdocumentation .

关于python - Python中如何自动暴露和修饰方法的函数版本?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9505341/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com