2013-04-04 61 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"