Class methods in Python
In Python, class methods are methods that are bound to the class and not the instance. They take the class itself as the first parameter, which is conventionally named cls.
They are declared using the @classmethod decorator.
Key Points about Class Methods:
- A class method receives the class (cls) as its first argument instead of the instance (self).
- It can be called on both the class itself and its instances.
- Class methods are often used for:
- Creating factory methods (alternative constructors).
- Working with class variables (shared across all objects).
Python
class MyClass:
class_variable = "Hello, I am a class variable"
@classmethod
def my_class_method(cls, value):
print("Class:", cls)
print("Class variable:", cls.class_variable)
print("Value passed:", value) Example: Calling Class Method.
Python
class Student:
school = "ABC School" # class variable
def __init__(self, name):
self.name = name
@classmethod
def get_school(cls):
return cls.school
# Call using class name
print(Student.get_school()) # Output: ABC School
# Call using object
s1 = Student("Ashish")
print(s1.get_school()) # Output: ABC School Example: Factory Method (Alternative Constructor).
Python
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
@classmethod
def from_string(cls, info):
name, age = info.split("-")
return cls(name, int(age)) # returning a new object
# Create object using normal constructor
p1 = Person("Katrina", 30)
# Create object using class method
p2 = Person.from_string("Ashish-29")
print(p1.name, p1.age) # Output: Katrina 30
print(p2.name, p2.age) # Output: Ashish 29 In short: • Use @classmethod when the method needs access to the class rather than the object.
• It is commonly used for alternative constructors or operations that involve class-level data.