0% found this document useful (0 votes)
9 views

Explaining OOP in Python using a Student class

The document explains Object-Oriented Programming (OOP) concepts in Python using a Student class as an example, covering principles such as abstraction, encapsulation, inheritance, and polymorphism. It provides illustrative code snippets demonstrating these concepts through a hierarchy of classes: Person, Student, and GraduateStudent. The summary emphasizes the importance of these principles in creating well-structured, reusable, and maintainable code.

Uploaded by

derbyfloral432
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views

Explaining OOP in Python using a Student class

The document explains Object-Oriented Programming (OOP) concepts in Python using a Student class as an example, covering principles such as abstraction, encapsulation, inheritance, and polymorphism. It provides illustrative code snippets demonstrating these concepts through a hierarchy of classes: Person, Student, and GraduateStudent. The summary emphasizes the importance of these principles in creating well-structured, reusable, and maintainable code.

Uploaded by

derbyfloral432
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 4

Explaining OOP in Python using a Student class as our central example.

To explain
these core concepts and then provide illustrative code snippets.

OOP (Object-Oriented Programming) Concepts

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.

Here are the key OOP principles:

●​ Abstraction: Hiding complex implementation details and exposing only essential


information. Think of it as showing a car's steering wheel and pedals to the driver,
without revealing the inner workings of the engine.
●​ Encapsulation: Bundling data (attributes) and methods (functions) that operate
on that data within a single unit (a class). It also involves protecting data from
direct access by making attributes private (using name mangling with double
underscores, e.g., __attribute).
●​ Inheritance: Creating new classes (child classes or subclasses) based on
existing classes (parent classes or superclasses). The child class inherits the
attributes and methods of the parent class and can add its own or override
existing ones. This promotes code reusability and a hierarchical structure.
●​ Polymorphism: The ability of an object to take on many forms. This can be
achieved through method overriding (where a child class provides a specific
implementation of a method already defined in the parent class) or through
method overloading (defining multiple methods with the same name but different
parameters, which Python achieves using default arguments and variable
argument lists).

Python Code Illustration with a Student Class

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}")

class Student(Person): # Inherits from Person


"""
Represents a student with name, age, student ID, and
courses.
Demonstrates Abstraction, Encapsulation, Inheritance, and
Polymorphism.
"""

def __init__(self, name, age, student_id):


super().__init__(name, age) # Call the parent class's
constructor
self.__student_id = student_id # Encapsulated (private)
attribute
self.courses = [] # List of courses the student is
enrolled in

# Getter method for student_id (Abstraction)


def get_student_id(self):
return self.__student_id

def enroll_course(self, course_name):


self.courses.append(course_name)
print(f"{self.name} enrolled in {course_name}")

def display_courses(self):
print(f"Courses for {self.name}: {',
'.join(self.courses)}")

# Method overriding (Polymorphism)


def display_info(self):
super().display_info() # Call the parent class's
display_info method
print(f"Student ID: {self.__student_id}")

# Polymorphism through a function that can work with


different objects
def study(self):
print(f"{self.name} is studying.")

class GraduateStudent(Student): #Inherits from Student


def __init__(self, name, age, student_id, thesis_topic):
super().__init__(name, age, student_id)
self.thesis_topic = thesis_topic

def study(self): #overrides the study method


print(f"{self.name} is researching for their thesis:
{self.thesis_topic}")

# 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()

def make_them_study(student): #function takes a Student object


student.study() # Polymorphism in action

make_them_study(student1) #student1 calls the Student version of


study()
make_them_study(student2) #student2 calls the GraduateStudent
version of study()

Explanation of the Code:

●​ Person Class: A base class to demonstrate inheritance. It has common


attributes like name and age, and a display_info method.
●​ Student Class:
○​ Inheritance: Student(Person) indicates that the Student class
inherits from the Person class. It gets the name and age attributes and
the display_info method. The super().__init__(name, age)
call in the Student constructor initializes the inherited attributes.
○​ Encapsulation: __student_id is a private attribute (name mangling). It
can only be accessed directly from within the Student class.
○​ Abstraction: The get_student_id() method provides controlled
access to the __student_id attribute. The user of the Student class
doesn't need to know how the student_id is stored internally. They just
use the get_student_id() method.
○​ Polymorphism (Method Overriding): The display_info method is
overridden in the Student class. When student1.display_info() is
called, it executes the Student class's version of the method, which also
calls the super class's version.
○​ Polymorphism (Function Argument): The make_them_study function
illustrates polymorphism. It takes a Student object as input and calls the
study() method. The specific study() method that gets called depends
on the actual type of the object passed to the function (either the Student
version or the GraduateStudentversion).
●​ GraduateStudent Class:
○​ Inheritance: Inherits from the Student class.
○​ Polymorphism (Method Overriding): The study() method is
overridden again in the GraduateStudentclass to provide a more
specific implementation for graduate students (related to their thesis).

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.

You might also like