2010-02-03 74 views
2

靜態方法,我知道這是連接到有這樣的情況下,但不知何故,我知道了:引用從類變量

class foo 
    #static method 
    @staticmethod 
    def test(): 
    pass 

    # class variable 
    c = {'name' : <i want to reference test method here.>} 

有什麼辦法呢?

只是爲了記錄:

我相信這應該被視爲蟒蛇最差實踐。使用靜態方法是不是真的如果有的話pythoish方式...

+1

如果可能,您應該考慮使用新式類。 – 2010-02-03 18:13:31

+3

這個Ruby或Python? – Chuck 2010-02-03 18:32:11

+0

另外,請注意通常不應該使用'staticmethod'。 Python對這個應用程序有正常的功能。 – 2010-02-03 18:32:11

回答

5
class Foo: 
    # static method 
    @staticmethod 
    def test(): 
     pass 

    # class variable 
    c = {'name' : test } 
3

的問題是在Python靜態方法是描述對象。因此,在下面的代碼:

class Foo: 
    # static method 
    @staticmethod 
    def test(): 
     pass 

    # class variable 
    c = {'name' : test } 

Foo.c['name']是描述符對象,因而是不調用。您必須輸入Foo.c['name'].__get__(None, Foo)()才能在此處正確呼叫test()。如果你不熟悉python中的描述符,看看the glossary,網上有很多文檔。另外,看看this thread,這似乎接近你的用例。

爲了簡單起見,你或許可以創建c類屬性外面的類定義的:

class Foo(object): 
    @staticmethod 
    def test(): 
    pass 

Foo.c = {'name': Foo.test} 

,或者,如果你覺得它的__metaclass__文檔中潛水。