Python Class Methods Examples
Short, runnable programs that show python class methods and static methods in action. Read the explanation, press Run, then change the code and try your own ideas. New to the topic? Start with the Python Class Methods and Static Methods lesson.
1Named presets with class methods
Class methods can build objects from fixed data. margherita() and veggie() need no arguments because the toppings are decided inside the class.
class Pizza:
def __init__(self, toppings):
self.toppings = toppings
@classmethod
def margherita(cls):
return cls(["tomato", "mozzarella"])
@classmethod
def veggie(cls):
return cls(["peppers", "mushrooms", "olives"])
def describe(self):
return " + ".join(self.toppings)
print(Pizza.margherita().describe())
print(Pizza.veggie().describe())
print(Pizza(["ham"]).describe())Expected outputtomato + mozzarella
peppers + mushrooms + olives
ham
2Building many objects from text
An alternative constructor is easy to use in a comprehension: one text line in, one finished object out, with the conversion to numbers done in one place.
class Product:
def __init__(self, name, price):
self.name = name
self.price = price
@classmethod
def from_string(cls, text):
name, price = text.split(",")
return cls(name.strip(), float(price))
def __repr__(self):
return f"Product({self.name!r}, {self.price})"
lines = ["Pen, 1.5", "Notebook, 3.25", "Bag, 24"]
products = [Product.from_string(line) for line in lines]
print(products)
print("Total:", sum(item.price for item in products))Expected output[Product('Pen', 1.5), Product('Notebook', 3.25), Product('Bag', 24.0)]
Total: 28.75
3A class method that manages class-level state
Ticket.take_number() hands out the next number and moves the shared counter on. reset_numbering() changes the class attribute through cls.
class Ticket:
next_number = 1
def __init__(self, event):
self.event = event
self.number = Ticket.take_number()
@classmethod
def take_number(cls):
number = cls.next_number
cls.next_number += 1
return number
@classmethod
def reset_numbering(cls, start=1):
cls.next_number = start
first = Ticket("Concert")
second = Ticket("Play")
print(first.number, second.number)
Ticket.reset_numbering(100)
third = Ticket("Opera")
print(third.number, Ticket.next_number)Expected output1 2
100 101
4A static method that belongs with its class
The rule for a valid username is part of the Account idea, so it lives in the class as a static method. It can be used before any account exists, and __init__ uses it too.
class Account:
def __init__(self, username):
if not Account.is_valid_username(username):
raise ValueError(f"invalid username: {username!r}")
self.username = username
@staticmethod
def is_valid_username(text):
return text.isalnum() and 3 <= len(text) <= 12
for name in ["asha99", "a!", "ben"]:
print(name, Account.is_valid_username(name))
try:
Account("x")
except ValueError as err:
print(err)Expected outputasha99 True
a! False
ben True
invalid username: 'x'
5What cls and self really are
A class method receives the class, whether you call it on the class or on an object. An instance method receives the object. Both calls to describe_class() show the same class.
class Gadget:
@classmethod
def describe_class(cls):
return f"cls is the class {cls.__name__}: {cls is Gadget}"
def describe_object(self):
return f"self is a {type(self).__name__} object: {self is not Gadget}"
phone = Gadget()
print(Gadget.describe_class())
print(phone.describe_class())
print(phone.describe_object())Expected outputcls is the class Gadget: True
cls is the class Gadget: True
self is a Gadget object: True
6Static method or plain function?
The conversion does not need the class, so the simplest design is a module-level function that the class (or anyone else) can call. No @staticmethod is needed.
def celsius_to_fahrenheit(celsius):
return celsius * 9 / 5 + 32
class Thermostat:
def __init__(self, celsius):
self.celsius = celsius
def fahrenheit(self):
return celsius_to_fahrenheit(self.celsius)
room = Thermostat(21)
print(room.fahrenheit())
print(celsius_to_fahrenheit(100))Expected output69.8
212.0
Practise next
Python Class Methods and Static Methods exercises → Back to the lesson
Python Functions examplesPython Class Attributes vs Instance Attributes examplesPython Dunder (Magic) Methods examples