Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Create a Python Class to Store and Query Student Information

Create a Python Class to Store and Query Student Information

Document Object Reference Manual Python3 Examples

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

)

:

       

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__ method is the class constructor, used to initialize the object's attributes. Here we initialize name、age and student_id three attributes.
  2. get_name、get_age and get_student_id are three methods used to get the student's name, age and student ID respectively.
  3. display_info The method prints all the information about a student.
  4. In the example usage section we create a Student object student1, and call the display_info method to display the student's information.

Output result:

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

Document Object Reference Manual Python3 Examples