我有这样的课:
class MyClass(object):
def f_1(self,x):
return foo(x, self.property_1)
def f_2(self,x):
return foo(x, self.property_2)
这个想法是多个函数f_n
具有共同的结构,但依赖于property_n
类的不同属性。
我寻找一种更紧凑的方式来f_n
定义__init__
? 我想到了类似的东西
class MyClass(object):
def __init__(self):
self.f_1 = self.construct_function(self.property_1)
self.f_2 = self.construct_function(self.property_2)
def construct_function(self, property):
# ???
这就是我的想法,但我不知道如何定义它construct_function
。'property' 是逐值类型是很重要的。
编辑:
我简化了Martijn对此解决方案的非常好的回答,效果很好:
def construct_function(property_name):
def f_n(self, x):
return foo(x, getattr(self, property_name))
return f_n
class MyClass2(object):
f_1 = construct_function('property_1')
f_2 = construct_function('property_2')
只是想在这里提一下,因为不允许多行注释...