I'd like to have a class decorator that adds properties to a class based on a class attribute _arg_names
, as in this minimal example:
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
However, when I run this, I find that all properties point to the last argument name:
>>> x = A()
>>> x.a
2
>>> x.b
2
Any ideas why the closure inside property
isn't working as expected? Are there any other solutions for this problem? I need the properties to be read-only, and they should show up in the class documentation.