MyInternships.in

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.

A normal instance method
Python
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.

A class method as an alternative constructor
Python
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.

A static method as a helper
Python
class MathHelper:
    @staticmethod
    def is_even(n):
        return n % 2 == 0

print(MathHelper.is_even(10))
TypeFirst ParamCan AccessCalled As
Instance methodselfobject data + class dataobj.method()
Class method (@classmethod)clsclass data onlyClassName.method() or obj.method()
Static method (@staticmethod)noneneither (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.

Related Python Topics

Keep learning with these closely related lessons.

Ready to use your Python skills?

Find Python, data science and software internships and fresher jobs across India.

Browse Python Internships