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.
self) |
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
沒有留言:
張貼留言