2006/11/29

lambda and property

if a property is bound to a specific method instance in a base class, and a derived method overrides the method, the property still remains bound to the original base class method.

Thus, we would have to also override the property in the derived class in order to get the desired behavior.


By binding the property to a lambda function that calls the desired method, when the method is overridden in a derived class, the property need not also be overridden in that derived class.

Special method names

Special method names
A class can implement certain operations that are invoked by special syntax (such as arithmetic operations or subscripting and slicing) by defining methods with special names.

This is Python's approach to operator overloading, allowing classes to define their own behavior with respect to language operators.

For instance, if a class defines a method named __getitem__(), and x is an instance of this class, then x[i] is equivalent to x.__getitem__(i).

__init__ defines the constructor for Class

__call__(self[, args...])
Called when the instance is ``called'' as a function; if this method is defined, x(arg1, arg2, ...) is a shorthand for x.__call__(arg1, arg2, ...).

__iter__(self)
This method is called when an iterator is required for a container. This method should return a new iterator object that can iterate over all the objects in the container.

__repr__( self)
``official'' string representation of an object.

class Employees:

#whatever ...

def __iter__(self):
self.startSomething()
employee = self.next()
while(employee != None):
yield employee
employee = self.next()
self.endSomething()

def totalCostOfManagers(emps):
total = 0
for employee in emps:
if employee.isManager: total = total + employee.salary
return total