Skip to content
Foxipa

Suggest an edit

Tell us what should be corrected, clarified, or improved. Submission will be connected to Foxipa’s contribution service later.

No information is sent anywhere yet. Your suggestion is only prepared in your browser.

Learning

Python Class Methods and Static Methods

Learn how Python class methods receive the class, how static methods receive no implicit object, and how to choose between method styles.

Levels: Intermediate ~22 min read

Intermediate

Python has three useful method styles: ordinary instance methods receive the instance, class methods receive the class, and static methods receive no implicit object. Choosing the right style makes a class interface easier to understand.

An ordinary method receives the instance

A normal method is called through an instance, so Python supplies that instance as the first argument, conventionally named self.

python
1
2
3
4
5
6
7
8
9
class Lamp:
    def __init__(self, name):
        self.name = name

    def describe(self):
        return f"{self.name} is ready"

lamp = Lamp("Desk lamp")
print(lamp.describe())

describe() is an instance method because it works with one particular Lamp object.

A class method receives the class

Apply @classmethod when the method needs the class itself. Python supplies the class as the first argument, conventionally named cls, whether the method is called through the class or an instance.

python
1
2
3
4
5
6
7
8
9
class Ticket:
    prefix = "T"

    @classmethod
    def label(cls, number):
        return f"{cls.prefix}-{number}"

print(Ticket.label(12))
print(Ticket().label(13))

Both calls supply Ticket as cls; an instance does not become the first argument.

Use a class method for alternate constructors

A class method can construct an instance by calling cls(...). This keeps the construction path compatible with subclasses: a subclass calling the inherited class method receives the subclass as cls.

python
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
class User:
    def __init__(self, name):
        self.name = name

    @classmethod
    def from_email(cls, email):
        name = email.split("@", 1)[0]
        return cls(name)

user = User.from_email("mina@example.com")
print(user.name)

from_email() provides an alternate constructor while still using the class that called it.

The class passed to a class method can be a subclass

Because cls is the class used for the call, an inherited class method can create the right subclass without hard-coding the base class name.

python
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
class Message:
    kind = "message"

    def __init__(self, text):
        self.text = text

    @classmethod
    def create(cls, text):
        return cls(text)

class Alert(Message):
    kind = "alert"

alert = Alert.create("Check the door")
print(type(alert).__name__)
print(alert.kind)

Alert.create() passes Alert as cls, so cls(text) creates an Alert instance.

A static method receives no implicit argument

Apply @staticmethod when a function belongs naturally to the class namespace but does not need either an instance or the class. Python does not insert self or cls.

python
1
2
3
4
5
6
7
class Temperature:
    @staticmethod
    def celsius_to_fahrenheit(celsius):
        return celsius * 9 / 5 + 32

print(Temperature.celsius_to_fahrenheit(20))
print(Temperature().celsius_to_fahrenheit(0))

The static method gets only the argument you explicitly pass.

Class and static methods can be called on an instance

Both styles can be accessed through a class or an instance. The difference is what Python supplies implicitly: cls for a class method and nothing for a static method.

python
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
class Formatter:
    @classmethod
    def label(cls, value):
        return f"{cls.__name__}: {value}"

    @staticmethod
    def upper(value):
        return value.upper()

formatter = Formatter()
print(formatter.label("ready"))
print(formatter.upper("ready"))

Accessing either method through formatter still does not turn the static method into an instance method.

Use class methods when the class matters

A class method is a good fit for behavior that reads or constructs through class-level state. Using cls instead of a hard-coded class name also lets inherited calls respect subclasses.

python
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
class Document:
    extension = ".txt"

    @classmethod
    def filename(cls, name):
        return f"{name}{cls.extension}"

class MarkdownDocument(Document):
    extension = ".md"

print(Document.filename("notes"))
print(MarkdownDocument.filename("notes"))

The same class method respects the extension defined by the class used for the call.

Use static methods when neither object nor class state matters

A static method is useful for a helper whose concept belongs with the class but whose calculation depends only on its explicit arguments. If a helper is equally unrelated to the class, a module-level function may be clearer.

python
1
2
3
4
5
6
7
class Order:
    @staticmethod
    def valid_quantity(quantity):
        return isinstance(quantity, int) and quantity > 0

print(Order.valid_quantity(3))
print(Order.valid_quantity(0))

valid_quantity() needs neither self nor cls, so staticmethod expresses that dependency clearly.

Compare the three method styles

Choose the method style by asking what the operation needs: instance state, class state, or only its explicit arguments. The syntax changes how Python binds the first argument.

python
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
class Sample:
    version = "1.0"

    def instance_method(self):
        return self.version

    @classmethod
    def class_method(cls):
        return cls.version

    @staticmethod
    def static_method(value):
        return value * 2

sample = Sample()
print(sample.instance_method())
print(Sample.class_method())
print(sample.static_method(4))

Instance methods receive self, class methods receive cls, and static methods receive no implicit argument.

Key takeaways

  • An instance method receives the instance as self.
  • A class method receives the class as cls and can be called through a class or instance.
  • A class method is useful for class-aware behavior and alternate constructors that should work with subclasses.
  • A static method receives no implicit self or cls; it uses only the arguments you pass explicitly.
  • Choose the method style based on whether the behavior needs instance state, class state, or neither.
Was this page helpful?

Mark this learning resource complete to track your learning progress.