I want to add properties dynamically to my class as follows, however I end up creating aliases. How can I prevent this?
class A:
def __init__(self, a, b):
self._a = a
self._b = b
for attr in ('a', 'b'):
f = lambda self: getattr(self, '_'+attr)
setattr(A, attr, property(f, None))
a = A(0,1)
print(a.a)
print(a.b)
However this yields:
1
1
Edit:
The comment on closure scoping is relevant, however that leaves the question whether one can generate properties dynamically that reference some attribute of self open.
Specifically with respect to the example above: how, if at all, can I set the property such that a.a returns 0 instead of 1? If I simply try to pass the attribute argument to the lambda function, this attribute will need to be passed and thus this won't work.