Person.name
is an instance of some type with a custom __eq__
method. While __eq__
normally returns a boolean(ish) value, it can actually return whatever you want, including a lambda. See Python special method names for more on this and related methods.
Probably the most confusing/misleading part of this (especially if you're used to other OO languages like Java) is that Person.name
and person.name
(where person
is an instance of Person
) don't have to have any relationship to each other. For example:
class Person(object):
name = "name of class"
def __init__(self):
self.name = "name of instance"
person = Person()
print Person.name
print person.name
This will print:
name of class
name of instance
Note that the class property is just set in the class body, while the instance property is set in the __init__
method.
In your case, you'd set Person.name
to the object with the custom __eq__
method that returns a lambda, something like this:
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)
This prints:
True
False
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.