Create a Python Class to Store and Query Student Information
We will create a class named Student Python class used to store basic student information (such as name, age, student ID, etc.) and provide methods to query that 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
)
:
(
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__method is the class constructor, used to initialize the object's attributes. Here we initializename、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 prints all the information about a student.- In the example usage section we create a
Studentobjectstudent1, and call thedisplay_infomethod to display the student's information.
Output result:
Name: Alice, Age: 20, Student ID: S12345
Python3 Examples