Python Reference Library →

Python classmethod() Function – Convert Method to Class Method

Let’s look at classmethod() function – convert method to class method

  1. Notice

    A classmethod receives the class as its first argument. It can construct instances using the class through which it was called.

  2. Try

    Follow the example, change its sample, and compare what happens.

  3. Check

    Explain the result and test your understanding.

Watch how it works

Focus on how the names, objects, and calculations change. We’ll inspect the printed output in the next section.

Explore the idea

Follow the code and watch its state change. Guided simulation.

Code
Python
class Score:
    def __init__(self, value):
        self.value = value
    @classmethod
    def from_text(cls, text):
        return cls(int(text))
score = Score.from_text('3')
print(score.value)
Live state

Top-level scope

Score→Object 2
score→Object 4
Object 2 · typeclass ScoreObject 4 · ScoreScore({'value': 3})
This step

A classmethod receives the class as its first argument. It can construct instances using the class through which it was called.

Picture classmethod() function – convert method to class method

A classmethod receives the class as its first argument. It can construct instances using the class through which it was called.

Image brief

Alt text
A diagram for Python classmethod() Function – Convert Method to Class Method. Instructions: class Score: def __init__(self, value): self.value = value @classmethod def from_text(cls, text): return cls(int(text)) score = Score.from_text('3') print(score.value). Displayed result: 3. The final example bindings are Score --> object 2 (type); score --> object 4 (Score). object 2: class Score; object 4: Score({'value': 3})
Image generation prompt
Create a clean educational illustration for a Python programming lesson titled "Python classmethod() Function – Convert Method to Class Method". Teaching focus: A classmethod receives the class as its first argument. It can construct instances using the class through which it was called. Depict exactly the relationships and labels in this reference diagram: EXAMPLE INSTRUCTIONS class Score: def __init__(self, value): self.value = value @classmethod def from_text(cls, text): return cls(int(text)) score = Score.from_text('3') print(score.value) | v DISPLAYED RESULT 3 FINAL BINDINGS Score --> object 2 (type) score --> object 4 (Score) object 2: class Score object 4: Score({'value': 3}) Use a flat vector style, generous spacing, clear arrows and legible labels, with a restrained blue/teal palette on a plain background. The diagram must explain the programming idea accurately. Do not depict variables as boxes containing copied objects when they share a reference. Avoid mascots, decorative screenshots, logos, gradients and extra text. Landscape composition, approximately 3:2, suitable for a course card. Accessible description: A diagram for Python classmethod() Function – Convert Method to Class Method. Instructions: class Score: def __init__(self, value): self.value = value @classmethod def from_text(cls, text): return cls(int(text)) score = Score.from_text('3') print(score.value). Displayed result: 3. The final example bindings are Score --> object 2 (type); score --> object 4 (Score). object 2: class Score; object 4: Score({'value': 3})

Follow the execution

Choose a different sample input, then follow every step through to the output. Before revealing it, predict what the program will display.

Execution workspace

Choose a sample and follow its execution. Guided simulation.

Code
Python
class Score:
    def __init__(self, value):
        self.value = value
    @classmethod
    def from_text(cls, text):
        return cls(int(text))
score = Score.from_text('3')
print(score.value)
Live state

Top-level scope

Score→Object 2
score→Object 4
Object 2 · typeclass ScoreObject 4 · ScoreScore({'value': 3})
This step

The example has finished. Compare the final output with the values and references above.

Terminal
Output
3

What do you expect this program to print?

What does this example display?

class Score:
    def __init__(self, value):
        self.value = value
    @classmethod
    def from_text(cls, text):
        return cls(int(text))
score = Score.from_text('3')
print(score.value)
What does this example display?
Choose one answer. You can try again.

Answer and explanation

3

Follow the printed values in order. The output is: 3

Which explanation matches what you learned?

Which explanation matches what you learned?
Choose one answer. You can try again.

Answer and explanation

A classmethod receives the class as its first argument. It can construct instances using the class through which it was called.

A classmethod receives the class as its first argument. It can construct instances using the class through which it was called.

More examples and reference

Python classmethod() Function

The classmethod() function in Python is used to define a method that belongs to the class rather than to any specific instance of the class. This means you can access and modify class-level data.

Syntax

classmethod(function)

Parameters:

  • function – The method you want to convert to a class method.

Returns:

  • A method that is bound to the class and not the instance.

Example: Defining a Class Method

class Person:
    species = "Human"

    def __init__(self, name):
        self.name = name

    @classmethod
    def get_species(cls):
        return cls.species

print(Person.get_species())
Human

How It Works

  • @classmethod is a decorator that makes the method receive the class (cls) as the first argument.
  • This allows the method to access or modify class-level attributes.

Alternative Without Decorator

class Demo:
    def normal_method():
        pass

Demo.class_method = classmethod(Demo.normal_method)

Real-World Use Case

Class methods are useful for creating factory methods—methods that return class instances using different input formats.

class Date:
    def __init__(self, year, month, day):
        self.year = year
        self.month = month
        self.day = day

    @classmethod
    def from_string(cls, date_str):
        y, m, d = map(int, date_str.split('-'))
        return cls(y, m, d)

d = Date.from_string("2025-05-14")
print(d.year, d.month, d.day)
2025 5 14

Difference Between classmethod() and staticmethod()

Feature classmethod() staticmethod()
First Parameter cls (the class) None
Access to Class Data Yes No
Typical Use Factory methods, altering class-level state Utility methods that don't access class or instance

Common Mistakes

  • Forgetting to use cls as the first argument in a class method.
  • Trying to access instance attributes directly—use instance methods for that instead.

Interview Tip

You may be asked to explain the difference between classmethod(), staticmethod(), and regular methods. Practice defining each one!

Summary

  • classmethod() binds a method to the class, not the instance.
  • Receives the class as the first argument (cls).
  • Useful for factory methods and working with class attributes.

Practice Problem

Create a class Book with a class method from_string() that takes a string like "Title-Author" and returns a new Book object.

class Book:
    def __init__(self, title, author):
        self.title = title
        self.author = author

    @classmethod
    def from_string(cls, book_str):
        title, author = book_str.split('-')
        return cls(title, author)

b = Book.from_string("Python101-John Doe")
print(b.title, b.author)
Python101 John Doe

What to remember

Connect what you noticed in the example with the idea below.

Remember

A classmethod receives the class as its first argument. It can construct instances using the class through which it was called.

Watch out for this idea

A classmethod always receives an instance as its first argument.

This is the misconception to avoid.

Reference checks are optional and do not count toward course progress.

    Reference library →