Python 使用decorator根据类属性注册数据

Python 使用decorator根据类属性注册数据,python,python-decorators,Python,Python Decorators,首先,这与XML序列化无关——它只是一个很好的用例,可以用作示例 我希望能够在类中标记属性,然后让序列化程序能够读取元数据并利用它 我已经看过了,但是这里的方法似乎只适用于方法而不适用于属性,而且我还需要接受标记装饰器outputasxmlcattribute&outputasxmlement中的参数 Python函数只是一个对象,可以接收其他属性。不幸的是,属性无法打开,因此必须将其展开。这意味着您可以从以下内容开始: def OutputAsXmlElement(label, schema)

首先,这与XML序列化无关——它只是一个很好的用例,可以用作示例

我希望能够在类中标记属性,然后让序列化程序能够读取元数据并利用它

我已经看过了,但是这里的方法似乎只适用于方法而不适用于属性,而且我还需要接受标记装饰器outputasxmlcattribute&outputasxmlement中的参数


Python函数只是一个对象,可以接收其他属性。不幸的是,属性无法打开,因此必须将其展开。这意味着您可以从以下内容开始:

def OutputAsXmlElement(label, schema):
    def deco(p):
        f = p.fget if isinstance(p, property) else p
        f._label = label
        f._schema = schema
        f._iselement = True
        return p
    return deco

def OutputAsXmlAttribute(label, schema):
    def deco(p):
        f = p.fget if isinstance(p, property) else p
        f._label = label
        f._schema = schema
        f._iselement = False
        return p
    return deco
然后通过inspect模块,您可以访问这些特殊属性。例如,以下是查找示例类的所有修饰成员及其标签和模式的方法:

for x, y in ((x,y) for x,y in inspect.getmembers(xmlInvoice.__class__)
         if not x.startswith('__')):
    if isinstance(y, property):
        f = y.fget
    else:
        f = y
    print(x, getattr(f, '_label', None), getattr(f, '_schema', None), getattr(f, '_element', None))

正是我想要的,谢谢。我尝试将数据固定到只读的属性对象时遇到了一个死胡同。
for x, y in ((x,y) for x,y in inspect.getmembers(xmlInvoice.__class__)
         if not x.startswith('__')):
    if isinstance(y, property):
        f = y.fget
    else:
        f = y
    print(x, getattr(f, '_label', None), getattr(f, '_schema', None), getattr(f, '_element', None))