Command Palette

Search for a command to run...

Hectal
Back to the lesson: Topic 8.3 — Instance, Class and Static Methods
Python · Example 1 of 2

Three kinds of method on a Pizza

Add a new alternative constructor, such as pepperoni(), that returns a 35 cm pizza with pepperoni.

Python has three kinds of method. An instance method works on one object (self), a class method works on the class itself (cls) and is the standard way to write alternative constructors, and a static method is a plain function that lives inside a class for organisation.

Change the code and press Run (Ctrl+Enter). Predict what will happen first, then break it on purpose and read what changes. Your edits are saved and match the lesson page.

Ready for more? This phase has 6 hands-on exercises with automatic checks.

Practice questions

Write the code in the editor, run it, then open the model answer to compare.

01

Write a class Temperature with attribute celsius, an instance method to_fahrenheit(), a class method from_fahrenheit(f) that builds one, and a static method is_freezing(c) that is true when c <= 0.

02

Write a class User with name and email, and a class method from_dict(data). Build a user from {"name": "Asha", "email": "a@x.com"} and print both attributes.

03

Make a subclass Admin(User) and show that Admin.from_dict(...) returns an Admin. Print the class name.

Explain it without notes

01

What is the difference between an instance method, a class method and a static method?

02

Why write return cls(...) in a class method instead of return ClassName(...)?

03

What is an alternative constructor, and why does Python use class methods for them?

04

What is a bound method?

Three kinds of method on a Pizza
Sign in to run this example in your browser.

Expected output

30cm pizza with ham
25cm pizza with corn, onion
30cm pizza with tomato, mozzarella
False True
method
True
True
True