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.
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.
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.
Make a subclass Admin(User) and show that Admin.from_dict(...) returns an Admin. Print the class name.
Explain it without notes
What is the difference between an instance method, a class method and a static method?
Why write return cls(...) in a class method instead of return ClassName(...)?
What is an alternative constructor, and why does Python use class methods for them?
What is a bound method?
Expected output
30cm pizza with ham
25cm pizza with corn, onion
30cm pizza with tomato, mozzarella
False True
method
True
True
True