DEV Community

Mahabubur Rahman
Mahabubur Rahman

Posted on

Python Inheritance

Create a parent class and initialize the variable.

class Teacher:

1. # Constructor this class variable
    def __init__(_self, name, sub):
        _self.name= name
        _self.sub = sub

2. # Get teacher Name
    def get_name(_self):
        return 'The Teacher Name : ' + _self.name

3. # Get teacher subject
    def get_sub(_self):
        return 'Subject : ' + _self.sub

Enter fullscreen mode Exit fullscreen mode

Output :

teacher = Teacher('Nur Alam', "Python / Graphic II")
print(teacher.get_name()) _# Output -> Nur Alam_
print(teacher.get_sub()) _# Output -> Python / Graphic II_
Enter fullscreen mode Exit fullscreen mode

Create a student class to inherit from the teacher class.

class Student(Teacher):

4. # Inherit to Change the subject and teacher on this student
    def change_teacher(_self, name, sub):
        _self.name = name
        _self.sub = sub

Enter fullscreen mode Exit fullscreen mode

Output :

student1 = Student("Tanvir", "IT Support")
print(student1.get_name()) _# Output -> Tanvir_
print(student1.get_sub()) _# Output -> IT Support_
Enter fullscreen mode Exit fullscreen mode

There, we are called the student class and access the teacher class methods.

Top comments (0)