Python:通过属性名获取静态属性

2 投票
2 回答
892 浏览
提问于 2025-04-16 14:53

我有一个Python类,通过元类实现了“模拟”的静态属性:

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

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


class My: __metaclass__ = MyMeta

现在我的一些函数会接收到一个属性名,作为字符串,这个属性名应该从My中获取。

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

这里的关键是我不想创建My的实例。

非常感谢,

Ovanes

2 个回答

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 的实例在运行。

3

你可以使用

getattr(My,name)

撰写回答