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 class1class Counter: # Class variable shared by the class and all its instances2 count = 03 # @classmethod passes the class itself as cls4 @classmethod5 def increment(cls): # Update the class variable through cls6 cls.count += 1 # Return the new count7 return cls.count8 # Called on the class, no instance needed: count goes 0 → 19print(Counter.increment())# The value persists on the class, so this prints 210print(Counter.increment())Output
1 2
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