the full guide

Methods

An instance method gets the object as self. A class method, marked @classmethod, gets the class as cls and is often used as an alternative constructor. A static method, marked @staticmethod, gets neither, and is an ordinary function kept inside the class.

8 min Intermediate

What you need: The earlier topics of this module.

Definition

An instance method gets the object as self. A class method, marked @classmethod, gets the class as cls and is often used as an alternative constructor. A static method, marked @staticmethod, gets neither, and is an ordinary function kept inside the class.

In simple words

Instance method: this student's result. Class method: create a student from a CSV line. Static method: a helper about marks in general, which needs no particular student.

Why it matters

You'll see all three in libraries. from_pretrained in Hugging Face, for instance, is a class method that builds a model object.

How it works

TypeFirst argumentCalled onUse for
InstanceselfAn objectUsing this object's data
@classmethodclsThe classOther ways to build objects
@staticmethodNoneEitherA related helper

In code

methods.py
class Student:
    pass_mark = 40

    def __init__(self, name, mark):
        self.name, self.mark = name, mark

    def passed(self):                     # instance method
        return self.mark >= self.pass_mark

    @classmethod
    def from_csv(cls, line):              # alternative constructor
        name, mark = line.split(",")
        return cls(name, int(mark))

    @staticmethod
    def grade(mark):                      # helper: no self or cls
        return "A" if mark >= 80 else "B"

riya = Student.from_csv("Riya,91")
print(riya.name, riya.passed())
print(Student.grade(91))

Output

Riya True
A

Common mistakes

  • Forgetting self in a method's parameters, which gives a confusing argument-count error.
  • Using a static method that needs the class. Use a class method so subclasses work.

Check yourself

Question 1

1. What is cls in a class method?

Question 2

2. Which suits an alternative constructor?

Summary

  • Instance methods use self, and class methods use cls.
  • Static methods are helpers that use neither.

Finished reading?

Sources: The Python Tutorial, python.org