2. What is a method?
• A method is similar to a function except it’s a member of
an object or class.
• Normally, we use the syntax object.method() to call a
method, for example datetime.now()
• The first parameter of an object method is always “self”
Example of method:
class Runner:
def run(self, meters):
pass
3. What are magic methods
• Special methods that you can define to add
“magic” to your classes
• Magic methods are surrounded by two
underscores, e.g. __init__
4. Some of the things we can
do with magic methods
• Give instructions to classes about what to do when creating an object
obj1 = MyClass() # __init__
!
• Explain classes how to arithmetically add together
obj1 + obj2 # __radd__
!
• Define how the object will look like when printed
print obj1 # __str__
• Explain classes how to perform boolean operations on them
obj1 > obj2 # __gt__, __lt__, __cmp__
5. The runners example
• We need to represent runners profile for a runners
website
• Each runner profile is related to a list of race statistics
• Each race statistic tracks distance ran and calories
used during the race
• We want to know: the total statistics for all races
(distance and calories) and to compare runners by
total distances made.
6. The runners example
class RaceStatistics:
def __init__(self, distance, calories):
self.distance = distance
self.calories = calories
!
def __radd__(self, other):
if other.__class__ == self.__class__:
return RaceStatistics(self.distance + other.distance,
self.calories + other.calories)
else:
return self