Sub topic 1
Classes are objects too
In Python, a class is a value like any other. This chapter shows what that means in practice. It also introduces type, the object that creates classes. Every later chapter builds on that idea.
Prerequisites
This chapter assumes you can:
- Define classes, methods and inheritance in Python.
- Call
super()inside methods. - Write and apply a basic decorator.
- Use keyword arguments and
**kwargs.
A class is a runtime value
A class statement does not only describe a shape for the compiler. When Python runs it, it creates an object and binds it to a name. You can treat that object like a number, a string or a function.
class Dog:
sound = "woof"
class Cat:
sound = "meow"
def make(cls):
return cls()
animals = {"dog": Dog, "cat": Cat}
pet = make(animals["cat"])
print(pet.sound) # meow
print(animals["dog"].sound) # woofThe code does three things that only work because classes are objects:
- It stores classes in a dictionary.
- It passes a class to a function.
- It calls the class through a variable named
cls.
This is the basis of factory functions, plugin tables and dependency injection.
Classes have attributes and can change
A class object carries data about itself. The most useful attributes are __name__, __bases__, __mro__ and __dict__.
class Animal:
pass
class Dog(Animal):
sound = "woof"
print(Dog.__name__) # Dog
print(Dog.__bases__) # (<class '__main__.Animal'>,)
print([c.__name__ for c in Dog.__mro__]) # ['Dog', 'Animal', 'object']
print("sound" in Dog.__dict__) # TrueYou can also change a class after it exists. Instances see the new attribute immediately, because attribute lookup checks the class at access time.
class Dog:
pass
d = Dog()
Dog.legs = 4
print(d.legs) # 4Every object has a type, including classes
Every object is an instance of exactly one class, and type(obj) returns it. A class is an object, so it has a type too.
class Dog:
pass
d = Dog()
print(type(d)) # <class '__main__.Dog'>
print(type(Dog)) # <class 'type'>
print(type(type)) # <class 'type'>
print(isinstance(Dog, type)) # TrueThe class type is the default class of classes. Python calls a class whose instances are classes a metaclass. So type is the standard metaclass. It is also its own type, which is where the chain stops.
Two relationships are easy to confuse:
| Relationship | Question it answers | How to check |
|---|---|---|
| Instance of | What created this object? | `type(obj)` or `isinstance` |
| Subclass of | What does this class inherit from? | `__bases__` or `issubclass` |
Dog is an instance of type and a subclass of object. These are separate facts.
print(isinstance(Dog, type)) # True
print(issubclass(Dog, object)) # True
print(isinstance(Dog, object)) # TrueThe last line is also true. Every class is an object, so isinstance(Dog, object) holds.
Why this matters for customization
If classes are objects, something creates them, and that creation can be customized. A normal object comes from calling its class. A class comes from calling its metaclass, which is type by default. The rest of this tutorial covers the ways to hook into that step.
Two habits help here:
- Use
type(x)when you want to know which class madex. This works for classes too. - Remember that a name like
Dogis a variable holding a class object. Rebinding the name does not change the class, and other references to the old class stay valid.
class Dog:
pass
Alias = Dog
Dog = None
print(Alias.__name__) # DogExercise
What does type(type(Dog)) return when Dog is an ordinary class defined with a class statement, and why?
Show answer
It returns <class 'type'>. type(Dog) is type because Dog is an instance of the default metaclass. type(type) is also type, because type is an instance of itself.
Exercise
Given class A: pass and class B(A): pass, which of these are true: isinstance(B, A), issubclass(B, A), isinstance(B, type)?
Show answer
issubclass(B, A) and isinstance(B, type) are true. isinstance(B, A) is false. B is a class object, not an instance of A, and its type is type.