Sub topic 2
Classmethods, Special Methods, Properties, and Inheritance
Assume you know Python functions, built-in types, control flow, and how to run Python 3 code. This chapter focuses on how methods receive context and how classes customize object behavior.
Classmethods and staticmethods
An instance method receives self, the current object. A classmethod receives cls, the class itself. It is useful for alternative constructors. A staticmethod receives neither automatically. It is a related utility function placed inside the class namespace.
class Pizza:
def __init__(self, toppings):
self.toppings = list(toppings)
@classmethod
def margherita(cls):
return cls(["mozzarella", "basil"])
@staticmethod
def valid_topping(name):
return name.isalpha()
pizza = Pizza.margherita()
print(pizza.toppings)
print(Pizza.valid_topping("ham"))Use a classmethod when the method must create or inspect instances of the calling class. Use a staticmethod when the operation needs no object or class state.
Making objects feel built-in with special methods
Special methods, often called dunder methods, have names such as __repr__, __eq__, and __add__. Python calls them for operations such as printing, comparison, and +.
class Vector:
def __init__(self, x, y):
self.x, self.y = x, y
def __repr__(self):
return f"Vector({self.x}, {self.y})"
def __add__(self, other):
if not isinstance(other, Vector):
return NotImplemented
return Vector(self.x + other.x, self.y + other.y)
print(Vector(1, 2) + Vector(3, 4))Return NotImplemented for unsupported operand types so Python can try the other operand's operation or raise an appropriate error.
Controlling attribute access with properties
A property presents a method as an attribute. This lets you validate assignments or calculate values without changing how callers use the object.
class Temperature:
def __init__(self, celsius):
self.celsius = celsius
@property
def celsius(self):
return self._celsius
@celsius.setter
def celsius(self, value):
if value < -273.15:
raise ValueError("below absolute zero")
self._celsius = value
@property
def fahrenheit(self):
return self._celsius * 9 / 5 + 32The leading underscore signals that _celsius is an implementation detail.
Reusing and overriding behavior with inheritance
Inheritance creates a subclass from a parent class. The subclass receives the parent's methods and can override them. super() calls the parent implementation.
class Animal:
def __init__(self, name):
self.name = name
def speak(self):
return "..."
class Dog(Animal):
def __init__(self, name):
super().__init__(name)
def speak(self):
return "Woof"
for animal in (Animal("Generic"), Dog("Rex")):
print(animal.name, animal.speak())Python searches for methods through the method resolution order (MRO), starting with the object's class and then its parent classes. Polymorphism lets the loop call speak() without checking each concrete type.
Exercise
Which decorator should you use for an alternative constructor that creates an instance of the calling subclass?
Show answer
Use @classmethod, because it receives the calling class through cls.