Python OOP
Python Class and Static Methods
Python classes support three kinds of methods — instance methods, class methods and static methods — each with a different relationship to the class and its objects.
Instance Methods (Recap)
Instance methods are the default kind: they take self as the first parameter and can read or change that specific object's attributes.
class Employee:
raise_percent = 5
def __init__(self, salary):
self.salary = salary
def apply_raise(self):
self.salary += self.salary * Employee.raise_percent / 100@classmethod
A class method takes cls (the class itself) instead of self, and is defined with the @classmethod decorator. It can read or change class variables shared by all objects, and is often used as an alternative constructor.
class Employee:
def __init__(self, name, salary):
self.name = name
self.salary = salary
@classmethod
def from_string(cls, data):
name, salary = data.split("-")
return cls(name, int(salary))
e = Employee.from_string("Rohit-45000")
print(e.name, e.salary)@staticmethod
A static method takes neither self nor cls. It behaves like a plain function that just happens to live inside the class, usually because it is logically related but does not need object or class data.
class MathHelper:
@staticmethod
def is_even(n):
return n % 2 == 0
print(MathHelper.is_even(10))| Type | First Param | Can Access | Called As |
|---|---|---|---|
| Instance method | self | object data + class data | obj.method() |
| Class method (@classmethod) | cls | class data only | ClassName.method() or obj.method() |
| Static method (@staticmethod) | none | neither (independent) | ClassName.method() or obj.method() |
Rule of thumb: use an instance method if you need self, a class method if you need the class but not a specific object, and a static method if you need neither.
Class methods are commonly used to create factory constructors, such as Employee.from_string(), that build objects from alternate input formats.
