Use instance method and class method properly

Use instance method and class method properly

This time, I will write about how to use instance methods and class methods properly.

Instance method

Use when you want to control the behavior for each instance

Class method

Used to control common behavior throughout the class

How to use instance method and class method in school as an example

school


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

Use instance method and class method properly
About Class and Instance
Python: Class and instance variables
Python class variables and instance variables
Python class definitions and instance handling
[Python] Difference between class method and static method
[Python] class, instance
Class method static method
Python class, instance
Camera calibration and use using opencv-python [chang method]
parallelization of class method
parallelization of class method
Method overriding and super
Use SQLAlchemy and multiprocessing
Metaclass and is instance
Class methods and static methods
How to use the __call__ method in a Python class
Reference order of class variables and instance variables in "self. Class variables" in Python
Various class methods and static methods
Use pyrtm and RTM CLI
Globalization of class instance variables
Perturbation development and simulation Perturbation method
Cumulative sum and potato method
Use and integration of "Shodan"
Class inheritance and super functions
Profile within a class method
I was addicted to confusing class variables and instance variables in Python
I thought a Python class variable was an instance variable and died