Create a Python class to implement storage and query of student information

Document 对象参考手册Python3 Examples

We will create a class namedStudentPython class for storing basic student information (such as name, age, student ID, etc.) and providing methods to query this information.

Example

class Student:
    def __init__(self, name, age, student_id):
        self.name = name
        self.age = age
        self.student_id = student_id

    def get_name(self):
        return self.name

    def get_age(self):
        return self.age

    def get_student_id(self):
        return self.student_id

    def display_info(self):
        print(f"Name: {self.name}, Age: {self.age}, Student ID: {self.student_id}")

# Example usage
student1 = Student("Alice", 20, "S12345")
student1.display_info()

Code analysis:

  1. __init__The method is the constructor of the class, used to initialize the object's attributes. Here, we initializedname、ageandstudent_idthree attributes.
  2. get_name、get_ageandget_student_idare three methods, used to get the student's name, age, and student ID respectively.
  3. display_infoThe method is used to print all information of the student.
  4. In the example usage section, we created aStudentobjectstudent1, and calleddisplay_infomethod to display the student's information.

Output result:

Name: Alice, Age: 20, Student ID: S12345

Document 对象参考手册Python3 Examples

Other extensions