在类装饰器中动态设置属性

时间:2018-06-06 22:25:46

标签: python oop properties python-decorators

我希望有一个类装饰器,它根据类属性_arg_names向类添加属性,如下例所示:

def add_properties(cls):
    for name in cls._arg_names:
        setattr(cls, name, property(lambda self: getattr(self, '_' + name)))
    return cls

@add_properties  # .a->._a, .b->._b
class A():
    _arg_names = ('a', 'b')
    def __init__(self):
        self._a = 1
        self._b = 2

但是,当我运行它时,我发现所有属性都指向最后一个参数名称:

>>> x = A()
>>> x.a
2
>>> x.b
2

为什么property内的闭包没有按预期工作的任何想法?这个问题还有其他解决方案吗?我需要将属性设置为只读,并且它们应该出现在类文档中。

0 个答案:

没有答案
相关问题