Methods in a Python class can be instance-level or class-level, similar to attributes.
An instance method is a method that is bound to an instance of a class. It can access and modify the instance data. An instance method is called on an instance of the class, and it can access the instance data through the self parameter.
A class method is a method that is bound to the class and not the instance of the class. It can’t modify the instance data. A class method is called on the class itself, and it receives the class as the first parameter, which is conventionally named cls.
Defining a class method is very convenient in Python. We can just add a built-in decorator named @classmethod before the declaration of the method.
Let’s see an example:
xxxxxxxxxx
class Student:
def __init__(self, first_name, last_name):
self.first_name = first_name
self.last_name = last_name
self.nickname = None
def set_nickname(self, name):
self.nickname = name
@classmethod # get_from_string is a class method
def get_from_string(cls, name_string: str):
first_name, last_name = name_string.split()
return Student(first_name, last_name)
s = Student.get_from_string('yang zhou')
print(s.first_name) # yang
print(s.last_name) # zhou
# can't call instance method directly by class name
s2 = Student.set_nickname('yang')
# TypeError: set_nickname() missing 1 required positional argument: 'name'