0Pricing
Python Academy · Lesson

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())   # woof

All lessons in this course

  1. How Python Classes Are Created
  2. Writing Custom Metaclasses
  3. Descriptors: __get__, __set__, __delete__
  4. __slots__ and Memory Optimization
← Back to Python Academy