python | Example of Class and Inheritance

25 阅读1分钟

Parent class: Human, attributes: Name, age, Method: Self-introduction

# Define the base class "Human"
class Human:
    def __init__(self, name, age):
        self.name = name
        self.age = age

    def introduce_self(self):
        print(f"My name is {self.name}, I'm {self.age} years old this year")


# Define the subclass "Student" (Inherited from "Human")
class Student(Human):
    def __init__(self, name, age, student_id, grade):
        super().__init__(name, age)
        self.student_id = student_id
        self.grade = grade

    def print_current_subject(self, subject):
        print(f"My name is {self.name}, my student ID is {self.student_id}, and I'm currently studying {subject}")


# ========== Call the class methods ==========
# 1. Call the "Human" class
person = Human(name="Zhang San", age=25)
person.introduce_self()

# 2. Call the "Student" class
student = Student(name="Li Si", age=18, student_id="20250001", grade="Senior 3")
student.introduce_self()
student.print_current_subject(subject="Python Programming")

image.png