CodeBlanks Logo Icon CodeBlanks

Factory pattern

Learn the factory pattern with @classmethod.

The factory pattern

The factory pattern lets you build an instance of a class from a different input. Usually a @classmethod returns a new instance; its name starts with from_....

Example: class User:\n @classmethod\n def from_birth_year(cls, name, year):\n return cls(name, 2025 - year). This method computes the age from the birth year and builds the instance. The caller only passes name and year; the age math is inside the method. This simplifies the call.

The from_ naming convention

Factory methods are usually named with a from_ prefix: from_list, from_string, from_dict. This helps the caller see at once that it is an alternate constructor.

Example: Counter.from_list([1, 2, 3]) builds an instance from a list. User.from_birth_year("Alex", 1990) builds one from a birth year. Readability improves this way; the call says what it does.

Practice Add a factory to User

Define the User class. Add def __init__(self, name, age): with self.name = name and self.age = age in the body. Add @classmethod and def from_birth_year(cls, name, birth_year):; in the body write return cls(name, 2025 - birth_year). Then create an instance with u = User.from_birth_year("Alex", 1990) and write print(u.age).

Starter code

main.py
# Add a factory to the User class

Sample solution

main.py
# Add a factory to the User class
class User:
    def __init__(self, name, age):
        self.name = name
        self.age = age
    @classmethod
    def from_birth_year(cls, name, birth_year):
        return cls(name, 2025 - birth_year)

u = User.from_birth_year("Alex", 1990)
print(u.age)

Expected output

35

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Match the factory concepts

Term Meaning
from_birth_year Factory method
cls(name, ...) New instance
2025 - year Age math

2 What does a factory method return?

  • The class name
  • An instance Correct answer
  • A method
  • None

Explanation: A factory method returns a new class instance.

3 Complete the factory return

Question
    @classmethod
    def from_birth_year(cls, name, year):
        return cls(name, 2025 - ____)
Answer
    @classmethod
    def from_birth_year(cls, name, year):
        return cls(name, 2025 - year)

Explanation: The year parameter is used in the age math.

All lessons in Intermediate