Weeks 13: More Classes and Objects
Why objects?
Objects provide encapsulation. In computer science, encapsulation can mean one of two related things:
-
A mechanism for restricting access to some of the object’s components.
-
A mechanism for bundling of data with methods operating on that data.
Classes and objects provide both mechanisms. On larger programming projects, it is common to have different people work on different parts of the program. Classes are a good place to divide the work. In this case, the class writer and the class user can agree on an interface. The interface specifies what methods the class has and what they should do. The class user doesn’t need to know or care how a class is implemented, only how to use the objects. The class writer doesn’t need to know or care how a class is used, only how to implement the interface.
Object-oriented programming also facilitates modularity. Modular programming is a software design technique that focuses on separating the functionality of a program into independent, interchangable pieces (aka "modules"), so that each piece contains everything needed to perform one aspect of the desired functionality.
Class definitions provide reusability, i.e., they let you create/reuse functionality while hiding technical details. With classes, you can rapidly create new and complex code by grabbing existing code "off the shelf" and reusing it for novel purposes.
More practice: a Course class
Let’s extend our Student example. In the file course.py, we will implement a Course class that represents a sample college course. At a mininum, each course should have a department (CPSC), a name (Intro to Computer Science), and a semester (F26). Feel free to add other attributes/member variables.
-
Write a constructor for your
Courseclass -
Write some getter methods for your
Courseclass. -
Write a
strmethod for yourCourseclass that returns a string representation of the course. For example, "CPSC: Intro to Computer Science (F26)". -
Write some test code to create a few
Courseobjects and print them out.
Adding courses to a Student
Import your Course class into your student.py file. Add a member variable to your Student class that is a list of courses. Add a method to your Student class that allows you to add a course to the student’s list of courses. Add a method to your Student class that returns the number of courses the student has taken. Update your str method for your Student class to include the number of courses the student is taking.
Add a search function to your Student class to find all courses that match a given semester.