Skip to contentSkip to navigation

Module 15 · Lesson 02

Class Methods and Static Methods

Know the three kinds of method: instance methods with self, class methods with cls for alternative constructors and class-wide state, and static methods for helpers, plus class attributes and their traps.

  • About 9 minutes
  • Builds on earlier lessons
  • 12-question quiz at the end

What you will learn

  • Shared class attributes
  • Another way in with a class method
  • Static helpers
  • Watch a class count its objects

Three kinds of method

A method can work on one object, on the whole class, or on neither.

  • Instance method

    Gets self, the one object it was called on.

  • Class method

    @classmethod gets cls, the class itself. Ideal for other ways to build an object.

  • Static method

    @staticmethod gets nothing extra: a helper that lives in the class.

  • Class attributes

    Set in the class body and shared by every object.

Class methods everywhere

The standard library uses class methods as friendly constructors.

  • Datesdate.fromisoformat("2026-11-28") builds a date from text.
  • Dictionariesdict.fromkeys(["a", "b"], 0) builds a dictionary of zeros.
  • FractionsFraction.from_float(0.5) turns a decimal into a fraction.
  • CountersA class attribute can count how many objects have been made.

Building an object another way

This line builds a Rect from text instead of two numbers. Tap each part to see its job.

Part 1 of 4

Tap any part of the code below, or press Next.1 of 4 explored

new object:A normal Rect, built by the class method.

Choose the right kind of method

Pick an example, change it, then press Run. Say what you expect to see before you press.

Example 1 of 6Shared attribute

sound lives on the class, so every cat can read it. name belongs to each cat.

Your turn: Add a second class attribute, legs = 4, and print it from both cats.

Python
class Cat:
    sound = "meow"

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

a, b = Cat("Tom"), Cat("Kit")
print(a.name, a.sound)
print(b.name, b.sound)
print(Cat.sound)
Output
Press Run to see what it prints.

Watch a class count its objects

Press Step to run one line at a time. Watch the names box change.

Ready. Press Step to run the first line.

  1. class Counter:
  2. made = 0
  3. def __init__(self, label):
  4. Counter.made += 1
  5. self.label = label
  6. @classmethod
  7. def total(cls):
  8. return cls.made
  9. a = Counter("a")
  10. b = Counter("b")
  11. print(Counter.total())
  12. print(a.made, b.label)

Output so far

Nothing printed yet.

What Python does

Python reads the program from the top. Nothing has run yet.

Names

None yet.

Quick guesses

Guess first, then read why. A wrong guess is where the learning happens. Nothing here is scored.

Question 1 of 6

1.A class method called on an object:

class A:
    @classmethod
    def who(cls):
        return cls.__name__
print(A().who())

0 of 6 answered

Common method misconceptions

Each card is something learners often believe. Tap it to see what Python really does.

Misconception 1 of 4

Notes

Everything above, in words. Open it when you want the full explanation.

Read the notesOpen

Class attributes and instance attributes

Attributes set on self belong to one object. Attributes written directly in the class body belong to the class and are shared by every object:

Try it 1: edit me, then Run
class Ticket:
    price = 12            # class attribute, shared

    def __init__(self, seat):
        self.seat = seat  # instance attribute, one per object

a = Ticket("A1")
b = Ticket("B7")
print(a.price, b.price)   # 12 12
Ticket.price = 15
print(a.price, b.price)   # 15 15
Output
Press Run to see what it prints.

When you read a.price, Python looks on the object first and then on its class. That lookup rule explains a common surprise: assigning through an object creates a new instance attribute that hides the class one, just for that object:

Try it 2: edit me, then Run
a.price = 10              # only a has its own price now
print(a.price, b.price)   # 10 15
Output
Press Run to see what it prints.

Use class attributes for constants and genuinely shared data, and change shared values through the class name, not through self.

Three kinds of method

Instance methods

The ordinary methods you already write. Python passes the object as the first argument, called self, so the method can read and change that object.

Class methods

Put @classmethod above a method and Python passes the class as the first argument instead, by convention named cls:

Try it 3: edit me, then Run
class Ticket:
    issued = 0

    def __init__(self, seat):
        self.seat = seat
        Ticket.issued += 1

    @classmethod
    def how_many(cls):
        return cls.issued
Output
Press Run to see what it prints.

You can call it on the class, Ticket.how_many(), or on any object, and either way it receives the class. Class methods are for behaviour that concerns the class rather than one object.

Alternative constructors

The most common use of a class method is an extra way to build objects. __init__ can only have one signature, but you can add as many named constructors as you like:

Try it 4: edit me, then Run
class Temperature:
    def __init__(self, celsius):
        self.celsius = celsius

    @classmethod
    def from_fahrenheit(cls, f):
        return cls((f - 32) * 5 / 9)

    @classmethod
    def from_text(cls, text):           # "21.5C" or "70F"
        value, unit = float(text[:-1]), text[-1].upper()
        return cls(value) if unit == "C" else cls.from_fahrenheit(value)

boiling = Temperature.from_fahrenheit(212)
print(boiling.celsius)                  # 100.0
Output
Press Run to see what it prints.

Names like from_fahrenheit, from_text or from_dict say exactly how the object is being made, which is clearer than an __init__ full of optional arguments and if branches.

Why cls and not the class name

Inside a class method, create objects with cls(...) rather than writing Temperature(...). When a subclass inherits the method, cls is the subclass, so the constructor builds the right type:

Try it 5: edit me, then Run
class Reading(Temperature):
    pass

r = Reading.from_fahrenheit(50)
print(type(r).__name__)                 # Reading
Output
Press Run to see what it prints.

Had the method written Temperature(...), Reading.from_fahrenheit would quietly return a plain Temperature. The same goes for class-wide data: cls.issued follows the class it was called on.

Static methods

A method marked @staticmethod receives no automatic first argument, neither the object nor the class. It is an ordinary function that lives inside the class because it belongs with it:

Try it 6: edit me, then Run
class Password:
    def __init__(self, text):
        if not Password.is_strong(text):
            raise ValueError("password too weak")
        self.text = text

    @staticmethod
    def is_strong(text):
        return len(text) >= 10 and any(c.isdigit() for c in text)

print(Password.is_strong("hunter2"))    # False
Output
Press Run to see what it prints.

Static methods suit small helpers such as validation, parsing or unit conversion that are clearly part of the class's job but need no state. Callers can use them before any object exists, as above.

Choosing

Ask what the method needs:

  • It reads or changes one object's data: an instance method with self.
  • It needs the class, to build objects or reach class-wide data, and should work for subclasses: a class method with cls.
  • It needs neither, but belongs with the class: a static method.
  • It needs neither and is useful on its own, not just for this class: a plain function in the module. Python does not force everything into classes, and a module-level function is often the simplest choice.

Mutable class attributes

One trap deserves its own warning. A list or dictionary written in the class body is a single object shared by all instances:

Try it 7: edit me, then Run
class Basket:
    items = []                 # shared by every basket!
    def add(self, item):
        self.items.append(item)
Output
Press Run to see what it prints.

Adding to one basket adds to all of them, because self.items.append finds the class list and changes it in place (no assignment, so no new instance attribute is created). Create per-object lists in __init__ with self.items = []. Keep mutable class attributes only when sharing is the point, such as a registry of every object created, and then access them through cls or the class name so the intent is clear.

Syntax

The general shape of the statements in this lesson.

syntax.py
class Thing:
    shared = 0                      # class attribute

    def __init__(self, x):
        self.x = x                  # instance attribute

    def method(self):               # instance method: gets the object
        return self.x

    @classmethod
    def from_text(cls, text):       # class method: gets the class
        return cls(int(text))       # cls(...) works for subclasses

    @staticmethod
    def helper(value):              # static method: gets nothing extra
        return value > 0

Thing.from_text("5")                # call on the class
Thing.helper(3)                     # or on an instance
obj.shared = 1                      # creates an instance attribute!
Thing.shared = 1                    # changes the shared one
Output
Press Run to see what it prints.

Worked examples

Read the problem, run the code, then read why it works.

Example 1 of 2

Several ways to create a booking

Beginner

Bookings arrive as objects, as text lines such as "Ana;3;2025-06-01" and as dictionaries from a web form. Give Booking one __init__ and two named class-method constructors, and count every booking created.

Python
class Booking:
    created = 0

    def __init__(self, name, guests, date):
        self.name = name
        self.guests = guests
        self.date = date
        Booking.created += 1

    def __repr__(self):
        return f"Booking({self.name!r}, {self.guests}, {self.date!r})"

    @classmethod
    def from_line(cls, line):
        name, guests, date = line.split(";")
        return cls(name.strip(), int(guests), date.strip())

    @classmethod
    def from_form(cls, form):
        return cls(form["name"], int(form.get("guests", 1)), form["date"])

bookings = [
    Booking("Ben", 2, "2025-06-01"),
    Booking.from_line("Ana; 3; 2025-06-01"),
    Booking.from_form({"name": "Cai", "date": "2025-06-02"}),
]
for booking in bookings:
    print(booking)
print("Bookings created:", Booking.created)
Output
Press Run to see what it prints.

Predict first

How it works(open after your guess)

Each class method only translates its input format and then calls cls(...), so all the real setup, including the counter, stays in __init__. The form constructor fills in a default of one guest. The counter is a class attribute changed through the class name, so every booking adds to the same number.

Common pitfalls

Mistakes people make with this topic, and what to write instead.

Pitfall 1 of 3

A shared list as a class attribute

Spot the bug

Can you see what is wrong? Run it to watch it go wrong, then open the fix.

Buggy code: run it
class Team:
    members = []
    def add(self, name):
        self.members.append(name)

red, blue = Team(), Team()
red.add('ana')
print(blue.members)
Output
Press Run to see what it prints.
Show what goes wrong and the fix

What happens

Prints ['ana']: the name appears in every team

Write this instead

class Team:
    def __init__(self):
        self.members = []
    def add(self, name):
        self.members.append(name)

red, blue = Team(), Team()
red.add('ana')
print(blue.members)

Why it happens

members is one list stored on the class, and append changes that one list.

In the real world

Where this shows up in software people use every day.

  1. Loading application settings

    Software configuration

    A service reads its settings from a key=value file in production and from a dictionary in tests. Defaults live in one class attribute, a static method parses yes/no values, and two class methods build the same Settings object from either source.

    Why Python fits

    __init__ is the single place where values are merged with the defaults and checked, so every constructor gets the same validation. The static parse_value is a pure helper that turns text into a bool, int or string. for_tests gives tests a ready-made configuration with a descriptive name instead of copied arguments.

    Python
    class Settings:
        DEFAULTS = {"debug": False, "workers": 2, "region": "eu"}
    
        def __init__(self, **values):
            unknown = set(values) - set(self.DEFAULTS)
            if unknown:
                raise ValueError(f"unknown settings: {sorted(unknown)}")
            self.values = {**self.DEFAULTS, **values}
    
        def __repr__(self):
            return f"Settings({self.values})"
    
        @staticmethod
        def parse_value(text):
            if text.lower() in ("yes", "true", "on"):
                return True
            if text.lower() in ("no", "false", "off"):
                return False
            return int(text) if text.isdigit() else text
    
        @classmethod
        def from_lines(cls, text):
            values = {}
            for line in text.splitlines():
                line = line.strip()
                if line and not line.startswith("#"):
                    key, raw = (part.strip() for part in line.split("=", 1))
                    values[key] = cls.parse_value(raw)
            return cls(**values)
    
        @classmethod
        def for_tests(cls):
            return cls(debug=True, workers=1)
    
    config_file = """# production
    workers = 8
    debug = off
    region = us"""
    
    print(Settings.from_lines(config_file))
    print(Settings.for_tests())
    try:
        Settings.from_lines("colour = blue")
    except ValueError as error:
        print("rejected:", error)
    Output
    Press Run to see what it prints.

Key takeaways

Tick each one you could explain to a friend.

0 of 5

Common questions

Guess the answer first, then open it.

Can a class method change instance attributes?

Not of an existing object directly, because it receives the class, not an object. It can create new objects with cls(...) and change class attributes. To change one object, use an instance method.

Why not just use a module-level function instead of a static method?

Often you should. A static method is worth it when the helper is clearly part of the class's job, such as validating that class's input, so that it travels with the class and can be overridden in a subclass.

Can I call a class method from an instance method?

Yes: self.from_text(...) or type(self).from_text(...) both work, and using them rather than the class name keeps subclasses working.

Are class methods the same as methods in other languages called static?

Not quite. Python's static methods match Java's or C#'s static methods. Class methods are extra: they receive the class, which makes inheritable alternative constructors possible.

Your notes

Sign in to keep private notes alongside this lesson.

Sign in to take notes

Where to go next

The quiz and the Lab live on their own pages, so this lesson stays about learning.

Finished this lesson?

Create an ID or sign in to save your progress across devices.

Create ID to save
Lessons done in this module0/3 complete
Quiz

Check what you learned

12 questions, with an explanation after every answer. A verified attempt counts towards opening the module Lab.

Lab

Keep going in the Lab

7 tasks on this lesson, from writing code to tracing it by hand. Practice only, no XP.

Review

Spaced review

Questions you miss in a quiz come back on a spaced schedule, so what you learned here sticks.

This lesson at a glance

The 16 lines of code this lesson uses, each with a short note. Keep it open while you do the quiz and the Lab.

What else you can search for and explore

Curious to go further? Each card opens a web search in a new tab.

References

Look things up here whenever you need the exact details.