I would like to create object properties using a loop, and the setattr function.
The problem i run into is that all the properties created with such a loop are equal to one another.
In the following example i create a class A with a single attribute z, a complex number. i then would like to loop over functions such as numpy's real and imag to create other properties, such as z_real and z_imag. The problem then, in the context of this example, is that z_real == z_imag is True.
import numpy as np
class A(object):
def __init__(self, z):
self.z = z
for func in [np.real, np.imag]:
fget = lambda x: func(x.z)
print('self.z_%s = %i' % (func.__name__, fget(self)))
setattr(self.__class__, 'z_%s' % (func.__name__),
property(fget))
a = A(1+2j)
print ('a.z_real=%i'% a.z_real)
print ('a.z_imag=%i'% a.z_imag)
running this yields
self.z_real = 1
self.z_imag = 2
a.z_real=2
a.z_imag=2
It is not clear to me why this is.