How Python Classes Are Created
Understand type, the default metaclass, and class creation hooks.
type() is a Metaclass
Every class in Python is an instance of type. type is itself a class — it is the metaclass of all metaclasses.
# These are equivalent:
class Dog:
sound = "woof"
Dog2 = type("Dog2", (), {"sound": "woof"})
print(type(Dog)) # <class 'type'>
print(type(Dog2)) # <class 'type'>type() Three-Argument Form
type(name, bases, namespace) creates a new class dynamically. This is exactly what class statements do under the hood.
Animal = type("Animal", (), {"speak": lambda self: "..."})
Dog = type("Dog", (Animal,), {"speak": lambda self: "woof"})
d = Dog()
print(d.speak()) # woofAll lessons in this course
- How Python Classes Are Created
- Writing Custom Metaclasses
- Descriptors: __get__, __set__, __delete__
- __slots__ and Memory Optimization