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>The normal/idomatic way to write a property is:</p>

<pre><code>class MyClass(object):
    def __init__(self):
        self._foo = 42

    @property
    def foo(self):
        return self._foo

    @foo.setter
    def foo(self, val):
        self._foo = val
</code></pre>

<p>as you can see, like all other method definitions in Python, the first parameter to the method is <code>self</code>.</p>

<p>You can name the parameter whatever you want (don't!), but the first parameter will always be the object itself.</p>

<p>The nice syntax above can be deconstructed to </p>

<pre><code>class MyClass(object):
    def __init__(self):
        self._foo = 42

    def foo_get(self):
        return self._foo

    def foo_set(self, val):
        self._foo = val

    foo = property(foo_get, foo_set)
</code></pre>

<p>and instead of passing function <em>names</em> to <code>property</code> we can instead use lambdas:</p>

<pre><code>class MyClass(object):
    def __init__(self):
        self._foo = 42

    def foo_set(self, val):
        self._foo = val

    foo = property(lambda self: self._foo, foo_set)
</code></pre>

<p>we can't pass the setter as a lambda since lambdas cannot contain assignments.  Here I've continued using <code>self</code> as the parameter name, but I could use any variable name, e.g.:</p>

<pre><code>foo = property(lambda u: u._foo, foo_set)
</code></pre>

python lambda