Junior — Middle
What is the difference between using methods declared as static and class in Python?
sobes.tech AI
Answer from AI
In Python, methods decorated with @staticmethod and @classmethod differ in how they access class and instance data:
-
@staticmethod — a method that does not automatically receive a reference to the instance (
self) or class (cls). It behaves like a regular function but is contained within the class for logical grouping. It cannot modify the state of the class or instance. -
@classmethod — a method that receives the class (
cls) as the first argument, not the instance. It can work with class attributes, create alternative constructors, and modify class state.
Example:
class MyClass:
count = 0
@staticmethod
def greet():
print("Hello!")
@classmethod
def increment_count(cls):
cls.count += 1
MyClass.greet() # Prints: Hello!
MyClass.increment_count()
print(MyClass.count) # Prints: 1
Thus, staticmethod is just a function inside a class, while classmethod is a method that works with the class itself.