Lesson 6 of 15 · Behaviour
Class Methods and Static Methods
Learn the difference between instance methods, class methods and static methods in Python, what cls means, and how to write alternative constructors.
- 7 min read
- Intermediate
- Reviewed
- What a decorator is, in simple terms
- What a class method is and what cls means
- How to give a class extra ways to create objects
- What a static method is and when to use one
- How to choose between the three kinds of method
Three kinds of method
Every method so far has received an object as self. Python has two more kinds of method, for jobs that do not need one particular object. To make them, you use a decorator.
You do not need to know how decorators work inside to use these two. (The Advanced Python course explains that.) Just place the line above the method.
Class methods
class Student:
school = "Velamuvi School"
count = 0
def __init__(self, name):
self.name = name
Student.count += 1
@classmethod
def how_many(cls):
return f"{cls.school} has {cls.count} students"
Student("Ada")
Student("Alan")
print(Student.how_many())You call a class method on the class itself: Student.how_many(). It works with class-level data, so it does not need any particular student.
The most common use: alternative constructors
A class can only have one __init__. But data often arrives in different shapes. A class method can accept that other shape, convert it, and then build the object normally.
class Temperature:
def __init__(self, celsius):
self.celsius = celsius
@classmethod
def from_fahrenheit(cls, fahrenheit):
celsius = (fahrenheit - 32) * 5 / 9
return cls(celsius)
def describe(self):
return f"{round(self.celsius, 1)} degrees Celsius"
today = Temperature(25)
oven = Temperature.from_fahrenheit(392)
print(today.describe())
print(oven.describe())cls(celsius) means "create an object of this class", exactly like writing Temperature(celsius). Using cls rather than the class name has a bonus you will see in the Inheritance lesson: it also works correctly for child classes.
Another very common case is building an object from a line of text, such as a row in a file:
class Student:
def __init__(self, name, age):
self.name = name
self.age = age
@classmethod
def from_text(cls, text):
name, age = text.split(",")
return cls(name.strip(), int(age))
rows = ["Ada, 17", "Alan, 16", "Grace, 18"]
students = []
for row in rows:
students.append(Student.from_text(row))
for student in students:
print(student.name, "is", student.age)Python programmers usually name alternative constructors starting with from_, such as from_text or from_file.
Static methods
class Password:
def __init__(self, text):
if not Password.is_long_enough(text):
raise ValueError("Password must have at least 8 characters")
self.text = text
@staticmethod
def is_long_enough(text):
return len(text) >= 8
print(Password.is_long_enough("abc"))
print(Password.is_long_enough("velamuvi2026"))
secure = Password("velamuvi2026")
print("Created a password with", len(secure.text), "characters")is_long_enough only needs the text you give it. It never uses self or cls. Keeping it inside Password simply keeps related code together, so readers know where to look.
Choosing the right kind
| Kind | Decorator | First parameter | Use it when the method needs... |
|---|---|---|---|
| Instance method | none | self | one object's data (most methods) |
| Class method | @classmethod | cls | the class, such as to create objects or read shared data |
| Static method | @staticmethod | none | neither: it is a helper related to the class |
A simple test: does the method use self? Then it is an instance method. Does it only use the class? Class method. Neither? Static method.
Common mistakes
Give a class a second way to create objects, plus a helper that needs no object.
# Write a class called Distance. # - __init__(self, metres) stores metres # - A class method from_km(cls, km) that returns a Distance of km * 1000 metres # - A static method is_valid(value) that returns True if value is 0 or more walk = Distance.from_km(2.5) print(walk.metres) print(Distance.is_valid(-3)) print(Distance.is_valid(10)) # Output must be exactly: # 2500.0 # False # True
What is the first parameter of a class method, and what does it hold?
Summary
- A decorator is an
@line above a method that changes how it works. - A class method (
@classmethod) receives the class ascls. Its most common use is an alternative constructor that ends withreturn cls(...). - A static method (
@staticmethod) receives nothing automatically. It is a helper that belongs with the class. - Most methods are instance methods. Use the other two only when you do not need an object.
Next: attributes that run code when you read or change them.
Finished reading? Tick it off to track your progress.