Class attribute, @classmethod, @staticmethod

Class method, class attribute, instance method, instance attribute, static method

  • Class method takes cls as the first parameter, it can access or modify the class state
  • Static method needs no specific parameters, it can't access or modify class or instance state

When to use class method?

  • As a factory, delicious pizza factories with @classmethod

Example

# Number of instance 
class CountedObject: 
	num_instances = 0
	def __init__(self): 
		self.__class__.num_instances += 1

>>> CountedObject.num_instances 0
>>> CountedObject().num_instances 1
>>> CountedObject().num_instances 2
>>> CountedObject().num_instances 3
>>> CountedObject.num_instances 3

Resources

SuperMade with Super