里面涉及到不同类性质类似于类的功能我有这样一个类:如何定义__init__
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
。 “财产”属于按价值类型是重要的。
编辑:
我简化Martijn's very good answer这个解决方案,它工作正常:
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')
只是想在这里提到它,因为多行注释不准......
难道这些功能常数*所有*实例,还是他们从实例有所不同的实例? – 2013-04-04 11:11:54
这些函数在结构上对于所有实例都是相同的,但当然取决于单个实例'self'的'self.propery_n'。 – flonk 2013-04-04 11:14:56
当然,像所有类的方法一样,self可用于查找属性。 – 2013-04-04 11:15:35