2011-04-01 88 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一个实例。

相关问题