Explaining OOP in Python using a Student class
Explaining OOP in Python using a Student class
To explain
these core concepts and then provide illustrative code snippets.
OOP is a programming paradigm built around the concept of "objects," which contain
data (attributes) and code (methods) to manipulate that data. It emphasizes modularity,
reusability, and maintainability.
python
class Person: # Base class for common attributes
def __init__(self, name, age):
self.name = name
self.age = age
def display_info(self):
print(f"Name: {self.name}, Age: {self.age}")
def display_courses(self):
print(f"Courses for {self.name}: {',
'.join(self.courses)}")
# Example Usage
student1 = Student("Alice", 20, "12345")
student2 = GraduateStudent("Bob", 25, "67890", "AI Ethics")
#inherits from the Student class
student1.enroll_course("Introduction to Python")
student1.enroll_course("Data Structures")
student1.display_courses()
student1.display_info() # Calls the overridden method
student2.enroll_course("Advanced AI")
student2.display_info()
In Summary
This example showcases how OOP principles can be applied in Python to create
well-structured, reusable, and maintainable code. By using classes, inheritance,
encapsulation, and polymorphism, you can model real-world entities and their
interactions in a clear and organized manner. Remember that this is a simplified
example; real-world applications often involve more complex class hierarchies and
interactions.