This time, I will write about how to use instance methods and class methods properly.
self
as the first argument@ classmethod
at the top of the methodcls
as the first argument of the class methodschool
class Class:
#Number of students enrolled in the entire school
all_students_count = 0
def __init__(self, teacher_name, grade, group):
self.teachername = teacher_name
self.grade = grade
self.group = group
self.roster=[]
def enter(self, name):
#Instance method
self.roster.append(name)
Class.all_students_count +=1
@classmethod
def reset_students_count(cls, reset):
#Class method
cls.all_students_count = reset
#Record enrollment in 2nd grade and 3rd class with instance method
cl_23 = Class("Yamanaka", 2, 3)
cl_23.enter("Hirasawa")
cl_23.enter("Akiyama")
cl_23.enter("Tainaka")
cl_23.enter("Kotobuki")
cl_23.enter("Manabe")
print("List of enrollees in 2nd grade and 3rd class" , cl_23.roster)
print(cl_23.all_students_count)
#output:List of enrollees in 2nd grade and 3rd class['Hirasawa', 'Akiyama', 'Tainaka', 'Kotobuki', 'Manabe'], 5
#Record one set of enrollees per year with instance method
cl_11 = Class("Toyota", 1, 1)
cl_11.enter("Kaneko")
cl_11.enter("Sato")
cl_11.enter("Shimizu")
print("List of enrollees per year" , cl_11.roster)
print(cl_11.all_students_count)
#output:List of enrollees per year['Kaneko', 'Sato', 'Shimizu'], 8
#Reset all enrollments with class method
Class.reset_students_count(0)
print(cl_11.all_students_count)
#output:0
Recommended Posts