OOP in Python Exercise
OOP in Python Exercise
Classes are defined in Python by using the class keyword, followed by the name of the
class and a colon. For example:
Class Pet:
The method __init__ is then used to declare the attributes to be used in each instance
of the class. For example:
def __init__(self, type, breed)
self.type = type
self.breed = breed
E.g. self.features.remove("Nose")
Attributes can be combined (concatenated) and returned for use elsewhere in a program
using a formatted string, or an “f string”. e.g.
return f"{self.type} {self.breed}"
For an easier to read representation of an object, the __str__ method can be used. E.g.
def __str__(self):
return f"Pet(type: {self.type}, breed: {self.breed},
features: {', '.join(self.features)}"
(.join will display each item in the list of features in a user friendly way)
Exercise
Student Management
Objective:
To practice object-oriented programming (OOP) concepts by creating a Python class for managing
student information.
Instructions:
courses (list of strings): A list of course names that the student is enrolled in.
__init__(self, student_id, first_name, last_name): The constructor method that initializes the
student's ID, first name, and last name. The courses attribute should be initialized as an empty list.
add_course(self, course_name): A method to add a course to the student's list of enrolled courses.
remove_course(self, course_name): A method to remove a course from the student's list of enrolled
courses.
get_full_name(self): A method that returns the student's full name in the format "First Name Last
Name".
__str__(self): A method that provides a user-friendly string representation of the student, including
their student ID, full name, and enrolled courses.
Test your Student class by performing the following actions in your Python script:
Create at least two Student objects with different student IDs, first names, and last names.
Add and remove courses for each student.
Display the student details using the __str__ method.
Hints:
Ensure that the __str__ method provides clear and readable information about each student.