Sub topic 1
Python Class Methods and Static Methods
Prerequisites
This chapter assumes you can define Python classes, create objects, write instance methods, use self, and distinguish class attributes from instance attributes. You should also recognize decorator syntax such as @classmethod.
Review: instance methods and `self`
An instance method operates on one object. Python passes that object as the first argument, conventionally named self.
class Temperature:
unit = "C"
def __init__(self, celsius):
self.celsius = celsius
def to_fahrenheit(self):
return self.celsius * 9 / 5 + 32
temperature = Temperature(20)
print(temperature.to_fahrenheit()) # 68.0When you call temperature.to_fahrenheit(), Python supplies temperature as self. The method can then read or change that object's attributes.
Review: class attributes versus instance attributes
A class attribute belongs to the class and is shared unless an instance defines an attribute with the same name. An instance attribute belongs to one object.
first = Temperature(20)
second = Temperature(30)
print(first.unit) # C
print(second.unit) # C
first.unit = "F"
print(first.unit) # F
print(second.unit) # CThe assignment creates unit on first; it does not change Temperature.unit or second.unit.
Class methods: methods that receive the class
A class method receives the class as its first argument, conventionally named cls. The @classmethod decorator changes how Python binds the method.
class Temperature:
def __init__(self, celsius):
self.celsius = celsius
@classmethod
def from_fahrenheit(cls, fahrenheit):
return cls((fahrenheit - 32) * 5 / 9)
temperature = Temperature.from_fahrenheit(212)
print(temperature.celsius) # 100.0Use a class method when the operation needs the class itself, such as creating an object or reading a class attribute.
Static methods: functions in a class namespace
A static method receives neither self nor cls. The @staticmethod decorator keeps the function in the class namespace without automatic binding.
class Temperature:
@staticmethod
def is_valid(celsius):
return celsius >= -273.15
print(Temperature.is_valid(-300)) # FalseUse a static method for a helper that logically belongs with the class but needs no object or class state.
Exercise
Which method type should validate an input value without reading an object or class attribute?
Show answer
A static method, because it needs neither self nor cls.