create properties with loop
<p>I would like to create object properties using a loop, and the <code>setattr</code> function.
The problem i run into  is that all the properties created with such a loop are equal to one another. </p>

<p>In the following example i create a class <code>A</code> with a single attribute <code>z</code>, a complex number. i then would like to loop over functions such as numpy's <code>real</code> and <code>imag</code> to create other properties, such as <code>z_real</code> and <code>z_imag</code>. The problem then, in the context of this example, is that <code>z_real == z_imag</code> is <code>True</code>.</p>

<pre><code>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)
</code></pre>

<p>running this yields</p>

<pre><code>self.z_real = 1
self.z_imag = 2
a.z_real=2    
a.z_imag=2
</code></pre>

<p>It is not clear to me why this is. </p>
