Classes and Objects
(Read time is about 1 minutes)
Consider this code
class Room():
def __init__(self, name, rmnum):
self.name = name
self.rmnum = rmnum
if self.rmnum > 100:
self.floor = (int(self.rmnum / 100) + 1)
else:
self.floor = 1
def __str__(self):
return "{0} on {1} with room number {2}".format(self.name, self.floor, self.rmnum)
So what is all this?
- First we create a class called Room.
- Then we define the initalizer or constructor which takes a room name and room number then generates floor number.
- Then we define the string function... that is so we can print(Room("P.E.", 20)) and get a valid statement back out.
So how do we use this class?
# Defining 6 classes
class1 = Room("English", 101)
class2 = Room("Science", 60)
class3 = Room("P.E.", 20)
class4 = Room("Mathmatics", 130)
class5 = Room("History", 88)
class6 = Room("Computer Programming", 99)
# Printing out these classes
print(class1)
print(class2)
print(class3)
print(class4)
print(class5)
print(class6)
So what all do we get?
English on 2 with room number 101
Science on 1 with room number 60
P.E. on 1 with room number 20
Mathmatics on 2 with room number 130
History on 1 with room number 88
Computer Programming on 1 with room number 99