In Python, @classmethod is a decorator used to define a method that is bound to the class and not the instance. It’s part of Python’s method types alongside @staticmethod and regular instance methods.
What is @classmethod?
• A @classmethod takes the class itself (cls) as its first argument, instead of self.
• It can access and modify class state that applies across all instances.
class Book:
count = 0
def __init__(self, title):
self.title = title
Book.count += 1
@classmethod
def get_count(cls):
return cls.count
Book("A Tale of Two Cities")
Book("1984")
print(Book.get_count()) # Output: 2
Here, get_count() is a class method used to read a class-level variable, not tied to a single instance.
⸻
🧠 When to Use @classmethod
• Factory methods (from_*) that return class instances:
class User:
def __init__(self, name, age):
self.name = name
self.age = age
@classmethod
def from_string(cls, user_str):
name, age = user_str.split(',')
return cls(name, int(age))
user = User.from_string("Alice,30")
• Accessing or modifying class-level state
• Supporting inheritance-aware behavior
class MathUtils:
@staticmethod
def square(x):
return x * x
print(MathUtils.square(4)) # Output: 16
Summary
• Use @classmethod when you need access to the class (cls)
• Use @staticmethod for utility functions that don’t need class or instance
• Use regular instance methods for behavior tied to an object
references:
OpenAI
No comments:
Post a Comment