2011-04-01 77 views
2

我通過元類與「模擬」靜態屬性蟒蛇類獲取靜態屬性:的Python:通過屬性名稱

class MyMeta(type): 
    @property 
    def x(self): return 'abc' 

    @property 
    def y(self): return 'xyz' 


class My: __metaclass__ = MyMeta 

現在我的一些函數接收屬性的名稱作爲一個字符串,它應該是從我的檢索。

def property_value(name): 
    return My.???how to call property specified in name??? 

這裏的重點是我不想創建My的實例。

非常感謝,

Ovanes

回答

3

你可以使用

getattr(My,name) 
+0

謝謝我確信已經嘗試過,並收到異常。但我試了一遍,它的工作....非常感謝! – ovanes 2011-04-01 13:33:51

0

我最近在看這一點。我希望能夠寫Test.Fu其中Fu是一個計算屬性。

使用描述對象的以下工作:

class DeclareStaticProperty(object): 
    def __init__(self, method): 
     self.method = method 
    def __get__(self, instance, owner): 
     return self.method(owner()) 

class Test(object): 
    def GetFu(self): 
     return 42 
    Fu = DeclareStaticProperty(GetFu) 

print Test.Fu # outputs 42 

注意,有分配的幕後Test一個實例。

相關問題