Sub topic 1
Classes are objects too
Prerequisites
You should know how to define classes, methods, and subclasses. You should also be comfortable with super() and keyword arguments.
Classes are objects too
In Python, a class is an object. Like other objects, it has a type. Most classes are instances of the built-in type class:
class Point:
pass
print(type(Point)) # <class 'type'>Point is an object that creates other objects. Calling Point() creates an instance of Point. Calling type(Point) tells you what created the Point class.
This relationship is useful because Python lets you customize class creation.
Creating classes with `type()`
The three-argument form of type() creates a class dynamically. It accepts:
- a class name
- a tuple of base classes
- a dictionary containing class attributes
Point = type(
"Point",
(),
{
"x": 0,
"describe": lambda self: f"Point at x={self.x}",
},
)
point = Point()
print(type(Point)) # <class 'type'>
print(point.describe()) # Point at x=0The empty tuple means that Point has no explicit base classes. The dictionary becomes the class namespace, which stores x and describe.
A normal class statement is usually easier to read. The dynamic form is useful when class names, bases, or attributes come from configuration or generated data.
What happens when Python runs a class statement
A class statement performs several steps:
- Python determines the base classes and chooses a metaclass. A metaclass is the object responsible for creating a class. The default metaclass is
type. - Python creates a namespace for the class body.
- Python executes the indented class body in that namespace.
- The metaclass creates the class object from the name, bases, and namespace.
- Python applies any class decorators.
The following diagram shows the central flow:
The metaclass can inspect or change the namespace before the class exists. Later chapters use this process to explain __init_subclass__, descriptors, and custom metaclasses.
Exercise
What does the three-argument form of type() use as the new class's attributes?
Show answer
It uses the dictionary passed as the third argument, called the class namespace.