Using Inheritance
Let s build an application that organizes info about people!
Person: name, birthday
Get last name Sort by last name Get age
Building a class
import datetime class Person(object): def __init__(self, name): """create a person called name""" [Link] = name [Link] = None [Link] = [Link](' ')[-1] def getLastName(self): """return self's last name""" return [Link] # other methods def __str__(self): """return self's name""" return [Link]
Building a class (more)
import datetime class Person(object): def __init__(self, name): """create a person called name""" [Link] = name [Link] = None [Link] = [Link](' ')[-1]
def setBirthday(self,month,day,year): """sets self's birthday to birthDate""" [Link] = [Link](year,month,day)
def getAge(self): """returns self's current age in days""" if [Link] == None: raise ValueError return ([Link]() - [Link]).days # other methods
How [Link]() works
Python uses the timsort algorithm for sorting sequences a highly-optimized combination of merge and insertion sorts that has very good average case performance The only knowledge needed about the objects being sorted is the result of a less than comparison between two objects Python interpreter translates obj1 < obj2 into a method call on obj1 obj1.__lt__(obj2) To enable sort operations on instances of a class, implement the __lt__ special method
Building a class (more)
import datetime class Person(object): def __init__(self, name): """create a person called name""" [Link] = name [Link] = None [Link] = [Link](' ')[-1]
def __lt__(self, other): """return True if self's ame is lexicographically less than other's name, and False otherwise""" if [Link] == [Link]: return [Link] < [Link] return [Link] < [Link] # other methods def __str__(self): """return self's name""" return [Link]