bhylu.com

Advertisements

Class Methods

Instance methods, class methods, and static methods receive different context. Choose the kind that matches what the operation actually needs.

Understand the idea

An instance method receives self. A classmethod receives cls and is useful for an alternative constructor that should respect subclasses. A staticmethod receives no implicit instance or class and can live on the class when that organisation is useful. Do not use a class method merely to avoid creating an instance when state is required.

Where to try it

Open this example with Try in playground. The code loads as editable text and does not run until you select Run. The first run downloads Python. Each run starts fresh; temporary files created by a script are not files on your PC.

A worked example

Python

class Workshop:
    def __init__(self, title):
        self.title = title
    @classmethod
    def from_text(cls, text):
        return cls(text.strip())

print(Workshop.from_text("  Python  ").title)

Read the result

The result is Python. cls constructs the requested class rather than hard-coding Workshop inside the factory.

Try one change

Subclass Workshop and show that from_text returns the subclass rather than the base class.