Class Method in Python

Level 4171 keystrokes

This uses a class method to access class-level data. The @classmethod decorator passes the class as the first argument.

Python code

# Define a class with class-level counter
1class Counter:
# Class variable shared by all instances
2 count = 0
3
# Constructor called when creating new instance
4 def __init__(self):
# Increment the class variable (not an instance attribute)
5 Counter.count += 1
6
# @classmethod receives class as first argument (cls)
7 @classmethod
# cls refers to the class itself, not instance
8 def get_count(cls):
# Return the class variable
9 return cls.count
10
# Create first instance, count becomes 1
11a = Counter()
# Create second instance, count becomes 2
12b = Counter()
# Call the class method and print the total count (2)
13print(Counter.get_count())

Output

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.

  • _× 6
  • (× 6
  • )× 6
  • =× 4
  • :× 3
  • .× 3
  • @× 1
  • +× 1

More Python examples at level 4

← Python typing practice