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
@classmethodgetscls, the class itself. Ideal for other ways to build an object.Static method
@staticmethodgets 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.
- Dates
date.fromisoformat("2026-11-28")builds a date from text. - Dictionaries
dict.fromkeys(["a", "b"], 0)builds a dictionary of zeros. - Fractions
Fraction.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
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.
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)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.
- class Counter:
- made = 0
- def __init__(self, label):
- Counter.made += 1
- self.label = label
- def total(cls):
- return cls.made
- a = Counter("a")
- b = Counter("b")
- print(Counter.total())
- 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:
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 notesNotesOpenClose
Syntax
The general shape of the statements in this lesson.
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 onePress 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
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.
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)Press Run to see what it prints.Predict first
How it works(open after your guess)
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.
class Team:
members = []
def add(self, name):
self.members.append(name)
red, blue = Team(), Team()
red.add('ana')
print(blue.members)Press Run to see what it prints.Show what goes wrong and the fixWhat goes wrong and the fix
In the real world
Where this shows up in software people use every day.
- Software configuration
Loading application settings
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 staticparse_valueis a pure helper that turns text into a bool, int or string.for_testsgives tests a ready-made configuration with a descriptive name instead of copied arguments.Pythonclass 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)OutputPress 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?
Why not just use a module-level function instead of a static method?
Can I call a class method from an instance method?
Are class methods the same as methods in other languages called static?
Your notes
Sign in to keep private notes alongside this lesson.
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.
Check what you learned
12 questions, with an explanation after every answer. A verified attempt counts towards opening the module Lab.
Keep going in the Lab
7 tasks on this lesson, from writing code to tracing it by hand. Practice only, no XP.
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.