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 counter1class Counter: # Class variable shared by all instances2 count = 03 # Constructor called when creating new instance4 def __init__(self): # Increment the class variable (not an instance attribute)5 Counter.count += 16 # @classmethod receives class as first argument (cls)7 @classmethod # cls refers to the class itself, not instance8 def get_count(cls): # Return the class variable9 return cls.count10 # Create first instance, count becomes 111a = Counter()# Create second instance, count becomes 212b = Counter()# Call the class method and print the total count (2)13print(Counter.get_count())Output
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.
_× 6(× 6)× 6=× 4:× 3.× 3@× 1+× 1