-
Notifications
You must be signed in to change notification settings - Fork 32
/
Copy pathlec12.2-mitperson.py
88 lines (73 loc) · 2.25 KB
/
lec12.2-mitperson.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
# lec12.2-mitperson.py
#
# Lecture 12 - Object Oriented Programming
# Video 2 - Using Inheritance Subclasses to Extend Behavior
#
# edX MITx 6.00.1x
# Introduction to Computer Science and Programming Using Python
import datetime
class Person(object):
def __init__(self, name):
"""create a person called name"""
self.name = name
self.birthday = None
self.lastName = name.split(' ')[-1]
def getLastName(self):
"""return self's last name"""
return self.lastName
def setBirthday(self,month,day,year):
"""sets self's birthday to birthDate"""
self.birthday = datetime.date(year,month,day)
def getAge(self):
"""returns self's current age in days"""
if self.birthday == None:
raise ValueError
return (datetime.date.today() - self.birthday).days
def __lt__(self, other):
"""return True if self's ame is lexicographically
less than other's name, and False otherwise"""
if self.lastName == other.lastName:
return self.name < other.name
return self.lastName < other.lastName
def __str__(self):
"""return self's name"""
return self.name
# me = Person("William Eric Grimson")
# print me
# me.getLastName()
# me.setBirthday(1,2,1927)
# me.getAge()
# her = Person("Cher")
# her.getLastName()
# plist = [me, her]
# for p in plist: print p
# plist.sort()
# for p in plist: print p
# MITPerson is a subclass of Person
class MITPerson(Person):
nextIdNum = 0 # next ID number to assign
def __init__(self, name):
# call Person's __init__ method
Person.__init__(self, name) # initialize Person attributes
# new MITPerson attribute: a unique ID number
self.idNum = MITPerson.nextIdNum
MITPerson.nextIdNum += 1
def getIdNum(self):
return self.idNum
# sorting MIT people uses their ID number, not name!
def __lt__(self, other):
return self.idNum < other.idNum
p1 = MITPerson('Eric')
p2 = MITPerson('John')
p3 = MITPerson('John')
p4 = Person('John')
# print p1
# p1.getIdNum()
# p2.getIdNum()
# p1 < p2
# p3 < p2
# p4 < p1
#
# Person and MITPerson __lt__ methods are different, Person does not have
# an IDNum, below will result in error.
# p1 < p4