This is one of those Python lines that looks mysterious until you realize it's just showing what Python does behind the scenes.
Let's start with the code you normally write:
Most people think this creates a class using some special Python magic.
What actually happens is that Python asks another object called type to create the class.
Behind the scenes, Python roughly does:
Let's decode each piece.
Step 1: What is type?
You've probably used it like this:
Output:
So it seems like type() tells you the type of an object.
But here's the twist:
Output:
Even classes themselves are objects.
And the thing that creates classes is type.
Think of it like this:
type is the "class factory."
Step 2: The first argument
First argument:
This is simply the class name.
Equivalent to:
Step 3: The second argument
This is a tuple containing parent classes.
Example:
has no explicit parent class, so:
means "no parent classes specified."
Another example:
would roughly become:
Notice the tuple contains Animal.
Step 4: The third argument
This dictionary contains everything inside the class body.
Example:
becomes approximately:
The dictionary is basically:
Visualizing the process
When Python sees:
it internally thinks something like:
So:
is roughly:
Proof
These two are essentially equivalent:
Normal syntax
Using type
Both work:
Output:
The big idea
There are objects, classes, and something that creates classes.
Think of a car factory:
In Python:
Example:
This idea becomes important later when learning metaclasses, because a metaclass is simply a custom replacement for type that can control how classes themselves are created.