Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p><code>Person.name</code> is an instance of some type with a custom <code>__eq__</code> method. While <code>__eq__</code> normally returns a boolean(ish) value, it can actually return whatever you want, including a lambda. See <a href="http://docs.python.org/reference/datamodel.html#special-method-names" rel="nofollow noreferrer">Python special method names</a> for more on this and related methods.</p> <p>Probably the most confusing/misleading part of this (especially if you're used to other OO languages like Java) is that <code>Person.name</code> and <code>person.name</code> (where <code>person</code> is an instance of <code>Person</code>) don't have to have any relationship to each other. For example:</p> <pre><code>class Person(object): name = "name of class" def __init__(self): self.name = "name of instance" person = Person() print Person.name print person.name </code></pre> <p>This will print:</p> <blockquote> <pre><code>name of class name of instance </code></pre> </blockquote> <p>Note that the class property is just set in the class body, while the instance property is set in the <code>__init__</code> method.</p> <p>In your case, you'd set <code>Person.name</code> to the object with the custom <code>__eq__</code> method that returns a lambda, something like this:</p> <pre><code>class LambdaThingy(object): def __init__(self, attrname): self.__attrname = attrname def __eq__(self, other): return lambda x: getattr(x, self.__attrname) == other class Person(object): name = LambdaThingy('name') def __init__(self, name): self.name = name equals_fred = Person.name == "Fred" equals_barney = Person.name == "Barney" fred = Person("Fred") print equals_fred(fred) print equals_barney(fred) </code></pre> <p>This prints:</p> <pre><code>True False </code></pre> <p>This is certainly skirting the edge of being "too clever", so I'd be very cautious about using this in production code. An explicit lambda would probably be a lot clearer to future maintainers, even if it is a bit more verbose.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload