2013-04-04 63 views
0

里面涉及到不同类性质类似于类的功能我有这样一个类:如何定义__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') 

只是想在这里提到它,因为多行注释不准......

+0

难道这些功能常数*所有*实例,还是他们从实例有所不同的实例? – 2013-04-04 11:11:54

+0

这些函数在结构上对于所有实例都是相同的,但当然取决于单个实例'self'的'self.propery_n'。 – flonk 2013-04-04 11:14:56

+0

当然,像所有类的方法一样,self可用于查找属性。 – 2013-04-04 11:15:35

回答

1

如果你想生成这些方法每类,请使用类装饰器:

def property_functions(**properties): 
    def construct_method(prop): 
     def f_n(self): 
      return foo(getattr(self, prop)) 
     return f_n 

    def class_decorator(cls): 
     for name, prop in properties.iteritems(): 
      setattr(cls, name, construct_method(prop)) 

     return cls 

    return class_decorator 

然后用它喜欢:

@property_functions(f_1='property_1', f_2='property_2') 
class MyClass(object): 
    property_1 = 'foo' 
    property_2 = 'bar' 

示范:

>>> def foo(value): print value 
... 
>>> @property_functions(f_1='property_1', f_2='property_2') 
... class MyClass(object): 
...  property_1 = 'foo' 
...  property_2 = 'bar' 
... 
>>> mc = MyClass() 
>>> mc.f_1() 
foo 
>>> mc.f_2() 
bar 
+0

这正是我所需要的。我认为它可以简化我的情况,即使没有装饰器,但您的基本想法(指定属性的*名称*作为字符串,然后使用'getattr')真的有帮助。 – flonk 2013-04-04 11:36:45

+0

最后减少到我的意思*更简单,没有装饰器*,请参阅原文中的编辑。再次感谢! – flonk 2013-04-04 11:49:05

+0

@flonk:这也很好。 :-)我的解决方案更通用一些,它可以用于多个类。 – 2013-04-04 11:56:19

0

你可以看看GETATTR的getAttribute。它们允许您动态创建和引用属性。对于前

它的工作原理是这样的:

class foo: 
    def __init__(self): 
     self.a = "a" 
    def __getattr__(self, attribute): 
     return "You asked for %s, but I'm giving you default" % attribute 


>>> bar = foo() 
>>> bar.a 
'a' 
>>> bar.b 
"You asked for b, but I'm giving you default" 
>>> getattr(bar, "a") 
'a' 
>>> getattr(bar, "b") 
"You asked for b, but I'm giving you default"