Python Classes and Inheritance
After completing this topic
You will understand what a class is and why it is needed. You will also learn how to define a class to create objects and how to reuse code through inheritance.
When you need a class
Let's say you need to manage student data. You could use a dictionary.
student1 = {"name": "Kim Hoon", "score": 90}student2 = {"name": "Lee Soo", "score": 85}
def get_grade(student): if student["score"] >= 90: return "A" elif student["score"] >= 80: return "B" return "C"The problem arises when the scale increases. If you need to add functions like "attendance check," "score modification," or "subject addition" for students, the functions will be scattered, and you'll have to search for "where is the student-related code?" every time.
A class groups data (attributes) and functions (methods) together.
Defining a class and creating an instance
class Student: def __init__(self, name, score): self.name = name # Instance attribute self.score = score def grade(self): if self.score >= 90: return "A" elif self.score >= 80: return "B" return "C" def introduce(self): return f"{self.name} ({self.grade()} grade)"# Create an instances1 = Student("Kim Hoon", 90)s2 = Student("Lee Soo", 85)
print(s1.introduce()) # Kim Hoon (A grade)print(s2.grade()) # Bs2.score = 92 # Modify the scoreprint(s2.grade()) # A__init__is the constructor β it is automatically called when an instance is created.selfis itself β it is the way to access the attributes of this instance.- When
Student("Kim Hoon", 90)is called,__init__(self, "Kim Hoon", 90)is executed.
Why use classes?
You can implement the same functionality with functions and dictionaries. The real value of a class is that it gathers "what can be done with this data" in one place.
# Function approach β data and functions are separatedstudent = {"name": "Kim Hoon", "scores": []}add_score(student, 90)get_average(student)get_grade(student)
# Class approach β data and functions are togetherstudent = Student("Kim Hoon")student.add_score(90)student.average()student.grade()When you type student., the IDE will show you a list of "what you can do with this object." The code itself acts as documentation.
Inheritance β inheriting common code
Both "students" and "professors" have "name" and "department." Put the common parts in the parent class and add the differences in the child class.
class Person: def __init__(self, name, department): self.name = name self.department = department def introduce(self): return f"{self.name} ({self.department})"
class Student(Person): def __init__(self, name, department, student_id): super().__init__(name, department) # Call the parent constructor self.student_id = student_id def introduce(self): return f"Student {self.name} ({self.student_id})"
class Professor(Person): def __init__(self, name, department, lab): super().__init__(name, department) self.lab = lab def introduce(self): return f"Professor {self.name} ({self.lab} lab)"s = Student("Kim Hoon", "Life Science", "2024-001")p = Professor("Park Jin", "Life Science", "Genomics")
print(s.introduce()) # Student Kim Hoon (2024-001)print(p.introduce()) # Professor Park Jin (Genomics lab)print(s.department) # Life Science β attribute inherited from Person- Use
super().__init__()to call the parent's constructor. - If the child class defines a method with the same name, it overrides the parent's method.
departmentis defined inPerson, but bothStudentandProfessorcan use it.
Key takeaways
| Concept | Meaning |
|---|---|
| Class | A blueprint that groups data (attributes) and functions (methods). |
| Instance | An actual object created from the blueprint (s1 = Student(...)). |
__init__ | Constructor β automatically executed when an instance is created. |
self | Refers to the current instance. |
| Inheritance | A child class inherits attributes/methods from the parent class. |
super() | Call a method from the parent class. |
| Override | The child class redefines a method from the parent class. |
There is no rule that you "must" use a class. For small scripts, functions and dictionaries are sufficient. However, when the code becomes larger and you need to handle multiple data with the same structure, classes are the most proven tool for organizing the code.