16. Python Class Inheritance with Examples (Video in Khmer)
Learn Python class inheritance with simple student and person examples, built-in functions, and tips for beginners.
2026-10-25 ยท 3 min read
Hello friend! ๐ Inheritance let one class use code from another class. The old class is called the parent. The new class is called the child.
In this post, I show you simple class and inheritance examples. ๐
๐ Useful Built-in Functions
Python has built-in functions to check an object and its class.
class Student:
pass
student = Student()
print(type(student).__name__) # Student
print(isinstance(student, Student)) # True
type() show the object's class. isinstance() check if an object belongs to a class.
๐ฅ Video: Built-in Functions for Class in Python (Khmer)
๐ Student Class with Score
Use __init__ to set data when you make an object.
class Student:
def __init__(self, name, score):
self.name = name
self.score = score
def show_score(self):
print(self.name, "score:", self.score)
student = Student("Dara", 95)
student.show_score() # Dara score: 95
name and score are attributes. show_score() is a method.
๐ฅ Video: Student Class with Score Example (Khmer)
๐งฌ Make a Child Class
Put the parent class name in brackets to inherit its attributes and methods.
class Person:
def __init__(self, name):
self.name = name
def say_hello(self):
print("Hello, I am", self.name)
class Student(Person):
def study(self):
print(self.name, "is studying")
student = Student("Dara")
student.say_hello() # Hello, I am Dara
student.study() # Dara is studying
Student get the name attribute and say_hello() method from Person.
๐ฅ Video: How to Use Inheritance in Python (Khmer)
๐ค Use super() with a Parent Class
Use super() to call the parent class setup code.
class Person:
def __init__(self, name):
self.name = name
class Student(Person):
def __init__(self, name, school):
super().__init__(name)
self.school = school
student = Student("Dara", "Green School")
print(student.name) # Dara
print(student.school) # Green School
super().__init__(name) set the name from the parent class.
๐ฅ Video: More Inheritance with Person Class (Khmer)
โ Common Error
Child class can use the parent setup only if you call it.
class Person:
def __init__(self, name):
self.name = name
class Student(Person):
def __init__(self, name, school):
super().__init__(name)
self.school = school
If you make Student.__init__(), remember to call super().__init__(name) when you need the parent's data.
๐ก Tips
- A parent class has shared code. A child class inherits that code.
- Use clear names, like
PersonandStudent. - Use inheritance when classes have something in common.
- Use
super()to call a parent method or setup. - Use
isinstance()to check an object's class. - Keep class code indented.
โ Any Question?
Tell us in comment below! ๐
#Python #Class #Object #Inheritance #LearnPython #Beginner