Class Method in Python

Level 4145 keystrokes

This uses @classmethod to create a method that receives the class as its first argument instead of an instance.

Python code

# Define a Counter class
1class Counter:
# Class variable shared by the class and all its instances
2 count = 0
3
# @classmethod passes the class itself as cls
4 @classmethod
5 def increment(cls):
# Update the class variable through cls
6 cls.count += 1
# Return the new count
7 return cls.count
8
# Called on the class, no instance needed: count goes 0 → 1
9print(Counter.increment())
# The value persists on the class, so this prints 2
10print(Counter.increment())

Output

1
2
Practice typing this code

Practice typing this code. Results are not recorded in the rankings.

Symbols in this code

The symbols you type in this Python code and how often they appear.

  • (× 5
  • )× 5
  • .× 4
  • :× 2
  • =× 2
  • @× 1
  • +× 1

More Python examples at level 4

← Python typing practice