Create a Python class to implement storage and query of student information
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()
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:
__init__The method is the constructor of the class, used to initialize the object's attributes. Here, we initializedname、ageandstudent_idthree attributes.get_name、get_ageandget_student_idare three methods, used to get the student's name, age, and student ID respectively.display_infoThe method is used to print all information of the student.- In the example usage section, we created a
Studentobjectstudent1, and calleddisplay_infomethod to display the student's information.
Output result:
Name: Alice, Age: 20, Student ID: S12345Other extensions
Python3 Examples