Python - Property Getter as a lambda with a parameter
<p>Being new to python I just came across the <code>property</code> keyword which basically lets you assign getters and setters. I came up with this simple example</p>

<pre><code>class foo:
    def __init__(self,var=2):
        self.var= var

    def setValue(self,var):
        print("Setting value called")
        self._var  = var

    def getValue(self):
        print("getting value")

    var = property(getValue,setValue)
</code></pre>

<p>Now in my django project I came across with something like this (using a lambda in a property)</p>

<pre><code>class UserProfile(models.Model):
    user = models.OneToOneField(User)
    likes_cheese = models.BooleanField(default=True)
    puppy_name = models.CharField(max_length=20)

User.profile = property(lambda u : UserProfile.objects.get_or_create(user=u)[0])
</code></pre>

<p>I had no clue that you could use a lambda inside a property. Now from what I understand is that it is setting the getter of the <code>profile</code> as a lambda and the getter requires a parameter. This kind of confused me. So I decided to try my own example</p>

<pre><code>class double:
    def setValue(self,var):
        print("Setting value called")
        self._var  = var

    def getValue(self):
        print("getting value")

    #var = property(getValue,setValue)
    var = property(lambda x: print("The value of parameter is" + str(x)))

d =double()
d.var #Call the getter but how do i pass a value parameter to it ? 
</code></pre>

<p>Now in my case how can i pass a parameter to the lambda ?</p>

<p>You probably want to do something like this.</p>

<pre><code>class double:
    def __init__(self):
        self._var = None

    var = property(lambda self: self._var,
                   lambda self, value: setattr(self, "_var", value))

d = double()
d.var = 3
print(d.var)
</code></pre>

<p>When you work with bound methods, the first parameter passed to them is always an instance of a class. It's named <code>self</code> in vast majority of the cases. But it's only a convention, you can name it whatever you want, so when you do just</p>

<pre><code>var = property(lambda x: print("The value of parameter is" + str(x)))
</code></pre>

<p><code>x</code> points to the instance, and <code>str(x)</code> is something like <code>&lt;__main__.double object at 0x105f47a90&gt;</code>, which is clearly not what you want.</p>

<p>Second, a getter doesn't accept any other arguments, because... well, you really don't need anything else but instance.</p>

<p>Third, we can also use a lambda as a setter; we need 2 parameters here, instance and value, but lambda cannot contain an assignment, so we gotta workaround it with <code>setattr()</code> function.</p>

<p>But if this approach used not just to train and explore, I'd recommend to fallback to <code>@property</code> syntax as shown by @thebjorn.</p>

python lambda