What is @classmethod in python
To understand what @classmethod in python is and how to use it
What is classmethod?
@classmethod is a function decorator.
class C: @classmethod def f(cls, arg1, arg2, ...):
A class method can be called either on the class (such as C.f()) or on an instance (such as C().f()). The instance is ignored except for its class. If a class method is called for a derived class, the derived class object is passed as the implied first argument.Python document >library >fuction
Features of class methods
- class methods can be called as the form Classname.method_name() without generate instance.
- class methods receive ‘cls’ not ‘self’ as argument.
How to use
Functions that access the internal data of the class can be managed collectively with class itself.
class Student: def __init__(self, name, grade): self.name = name self.grade = grade @classmethod def testpoint_to_grade(cls, name, testpoint): if testpoint > 90: return cls(name, 'A') elif testpoint > 80: return cls(name, 'B') elif testpoint > 60: return cls(name, 'C') else: return cls(name, 'D') def print_grade(self): print(self.grade) student1 = Student('Alice', 'C') student2 = Student.testpoint_to_grade('Ben', 85) student1.print_grade() >> C student2.print_grade() >> B