Classes in Python allow you to create blueprints for objects. These objects can have attributes (characteristics) and methods (functions) associated with them. By using classes, you can organize your code more effectively, encapsulate data and functionality, and create reusable components.
Suppose we want to create a student management system where we can store information about students, such as their name, age, and grades, and perform actions like adding new students, calculating average grades, and displaying student information.
Student Classclass Student:
def __init__(self, name, age):
self.name = name
self.age = age
self.grades = [] def add_grade(self, grade):
self.grades.append(grade) def calculate_average_grade(self):
if len(self.grades) == 0:
return 0
else:
return sum(self.grades) / len(self.grades) def display_info(self):
print(f"Name: {self.name}, Age: {self.age}, Grades: {self.grades}, Average Grade: {self.calculate_average_grade()}")
In this class:
Student class with attributes name, age, and grades.add_grade, calculate_average_grade, and display_info to perform actions related to students.# Create students
student1 = Student("Alice", 18)
student2 = Student("Bob", 17) # Add grades
student1.add_grade(85)
student1.add_grade(90)
student2.add_grade(75)
student2.add_grade(80)
student2.add_grade(95) # Display student information
student1.display_info()
student2.display_info()
In this step:
Student class representing different students.add_grade method.display_info method.Classes in Python provide a way to model real-world entities and their behaviors. In this example, we created a Student class to represent students and demonstrated how to create instances of this class, add grades, and display student information.
By using classes, you can create modular, reusable components, making your code more organized and easier to maintain. This example provides a basic introduction to classes in Python, but there's much more you can do with classes, such as inheritance, polymorphism, and encapsulation, which we can explore further in future tutorials.
Let's extend the student management system example by introducing a Course class to manage courses and enroll students in them.
Course Classclass Course:
def __init__(self, course_name, max_students):
self.course_name = course_name
self.max_students = max_students
self.students_enrolled = [] def enroll_student(self, student):
if len(self.students_enrolled) < self.max_students:
self.students_enrolled.append(student)
print(f"{student.name} enrolled in {self.course_name} course.")
else:
print(f"Cannot enroll {student.name}. Course is full.") def display_students(self):
print(f"Students enrolled in {self.course_name} course:")
for student in self.students_enrolled:
print(student.name)
In this class:
Course class with attributes course_name, max_students, and students_enrolled.enroll_student to enroll students in the course and display_students to display the list of enrolled students.# Create courses
math_course = Course("Math", 3)
english_course = Course("English", 2) # Enroll students in courses
math_course.enroll_student(student1)
math_course.enroll_student(student2)
english_course.enroll_student(student1)
english_course.enroll_student(student2) # Display students enrolled in each course
math_course.display_students()
english_course.display_students()
In this step:
Course class representing different courses.enroll_student method.display_students method.By extending the student management system example with the Course class, we demonstrated how to use classes to model complex relationships between entities (students and courses) in a real-world scenario. Classes allow us to encapsulate data and functionality, making our code more modular, reusable, and maintainable.
This example highlights the power and flexibility of classes in Python for modeling and managing real-world entities and their interactions. There's still much more you can explore and extend with classes, such as implementing additional methods, handling edge cases, and incorporating more features into your application.
Python Mega Course: Learn Python in 60 Days, Build 20 Apps
Learn Python on Udemy completely in 60 days or less by building 20 real-world applications from web development to data science.
