Previous Lecture Lecture 3 Next Lecture

Lecture 3, Tue 04/11

Python Classes

Recorded Lecture: 4_11_23

Python Objects and Classes

>>> x = [1,2,3]
>>> type(x)
<class 'list'>
>>> x.count(3)
1
>>> x.count(-1)
0
>>> x.append(0)
>>> x
[1, 2, 3, 0]

Student Class Example

class Student:
	''' Student class type that contains attributes for all students '''
	def setName(self, name):
		self.name = name

	def setPerm(self, perm):
		self.perm = perm

	def printAttributes(self):
		print("Student name: {}, perm: {}" \
		.format(self.name, self.perm))

s = Student()
s.setName("Chris Gaucho")
s.setPerm(1111111)
s.printAttributes()

Default Constructor

def __init__(self):
	self.name = None
	self.perm = None

s = Student()
s.printAttributes()

Overloading Constructors

def __init__(self, name, perm):
	self.name = name
	self.perm = perm

s = Student("Richert", 1234567)
s.printAttributes()

Initializing default values in the constructor

def __init__(self, name=None, perm=None):
	self.name = name
	self.perm = perm
s = Student(perm=1234567)
s.printAttributes()

# Student name: None, perm: 1234567

Example of using objects in code

s1 = Student("Jane", 1234567)
s2 = Student("Joe", 7654321)
s3 = Student("Jill", 5555555)

studentList = [s1, s2, s3]

for s in studentList:
	s.printAttributes()

# Using assert statements to test correct functionality
s1 = Student()
assert s1.name == None
assert s1.perm == None

s1 = Student("Gaucho", 7654321)
assert s1.name == "Gaucho"
assert s1.perm == 7654321

Container Classes

# Courses.py

# from [filename (without .py)] import [component]
from Student import Student 

class Courses:
	''' Class representing a collection of courses. Courses are
		organized by a dictionary where the key is the
		course number and the corresponding value is
		a list of Students of this course '''

	def __init__(self):
		self.courses = {}

	def addStudent(self, student, courseNum):
		# If course doesn't exist... 
		if self.courses.get(courseNum) == None:
			self.courses[courseNum] = [student]
		elif not student in self.courses.get(courseNum):
			self.courses[courseNum].append(student)

	def printCourses(self):
		for courseNum in self.courses:
			print("CourseNum: ", courseNum)
			for student in self.courses[courseNum]:
				student.printAttributes()
			print("---")

	# Getter method
	def getCourses(self):
		return self.courses


# Using assert statements to test correct functionality
s1 = Student("Gaucho", 1234567)
UCSB = Courses()
UCSB.addStudent(s1, "CS9")
courses = UCSB.getCourses()

assert courses == {"CS9": [s1]}