CodeBlanks Logo Icon CodeBlanks

@classmethod

Learn class methods with @classmethod.

The @classmethod decorator

The @classmethod decorator takes cls as its first parameter. cls is the class itself, not an instance. This is useful for class-level operations.

Example: class Counter:\n @classmethod\n def from_list(cls, items):\n return cls(len(items)). In Counter.from_list([1, 2, 3]) cls is Counter; cls(len(items)) creates a new instance. This pattern is common as an alternate constructor.

What does cls represent?

cls is the class that calls the method. It gives access to the class, not instance data. Writing cls(...) creates a new instance; this makes alternate constructors easy.

Example: in Counter.from_list([1, 2, 3]) cls is Counter. With cls(len(items)) a Counter(3) instance is built. This also works in subclasses; cls is always the calling class.

Practice Add a classmethod to Counter

Define the Counter class. Add def __init__(self, count): with self.count = count in the body. Add @classmethod and def from_list(cls, items):; in the body write return cls(len(items)). Then create an instance with c = Counter.from_list([1, 2, 3]) and write print(c.count).

Starter code

main.py
# Define the Counter class

Sample solution

main.py
# Define the Counter class
class Counter:
    def __init__(self, count):
        self.count = count
    @classmethod
    def from_list(cls, items):
        return cls(len(items))

c = Counter.from_list([1, 2, 3])
print(c.count)

Expected output

3

Questions and answers

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

1 Complete the classmethod signature

Question
class Counter:
    @classmethod
    def from_list(____, items):
        return cls(len(items))
Answer
class Counter:
    @classmethod
    def from_list(cls, items):
        return cls(len(items))

Explanation: @classmethod takes cls as its first parameter.

2 What is the first parameter of @classmethod?

  • cls Correct answer
  • self
  • this
  • class

Explanation: @classmethod takes cls as its first parameter.

3 Match the classmethod concepts

Term Meaning
@classmethod Decorator
cls Class reference
cls(len(items)) New instance

All lessons in Intermediate