Command Palette

Search for a command to run...

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

Alternative constructors for chat messages

AI code constantly turns dictionaries from JSON into objects. Note that LoudMessage.from_dict returns a LoudMessage because it uses cls. The line super().__init__(...) in LoudMessage runs the parent class's setup; Topic 8.5 teaches it.

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?

Alternative constructors for chat messages
Sign in to run this example in your browser.

Expected output

Message('user', 'Hello')
Message('assistant', 'Hi there')
LoudMessage('assistant', 'HI THERE')
LoudMessage
{"role": "user", "content": "Hello"}