Meaning of @classmethod and @staticmethod for beginner
In Python, @classmethod
is a decorator that is used to define a method as a class method. A class method is a method that is bound to the class and not the instance of the class.
A class method is a method that belongs to a class rather than an instance of the class. They can be called on the class itself, as well as on any instance of the class.
Here's an example of how to use the @classmethod
decorator:
class MyClass:
def __init__(self, name, age):
self.name = name
self.age = age
@classmethod
def from_string(cls, string):
name, age = string.split(',')
return cls(name, age)
person1 = MyClass('John', 30)
print(person1.name, person1.age)
person2 = MyClass.from_string('Jane, 25')
print(person2.name, person2.age)
In the example above, the from_string
method is a class method. It is defined using the @classmethod
decorator and takes a cls
parameter, which refers to the class itself. The from_string
method can be called on the MyClass
class, as well as on any instance of the MyClass
class.
On the other hand, @staticmethod
is a decorator that is used to define a static method. A static method is a method that belongs to a class rather than an instance of the class, but it does not have access to the class or instance. It is a method that is bound to the class and not the instance of the class.
Here's an example of how to use the @staticmethod
decorator:
class MyClass:
def __init__(self, name, age):
self.name = name
self.age = age
@staticmethod
def greet():
print('Hello, world!')
person = MyClass('John', 30)
MyClass.greet()
person.greet()
In the example above, the greet
method is a static method. It is defined using the @staticmethod
decorator and does not take any special parameters. The greet
method can be called on the MyClass
class, as well as on any instance of the MyClass
class.