Sub topic 1
Classes are objects too
In Python, a class is a value, like an integer or a list. You can assign it to a name, pass it to a function, store it in a dictionary and inspect it at runtime. Every later chapter in this tutorial builds on that fact. A metaclass is a class whose instances are classes, and a hook like __init_subclass__ is code that runs when a class object is created. Both ideas only make sense once you accept that a class is a real object that something creates.
This chapter builds that mental model. It does not yet show how classes are built. That comes in the next chapters.
Prerequisites
This chapter assumes you can:
- Define classes with methods and use single inheritance.
- Use
isinstanceandtype()to check what an object is. - Read a small function that returns another function or class.
You do not need to know anything about metaclasses yet.
Everything is an object
An object in Python is a value with an identity, a type and some attributes. Integers, strings, functions and modules are all objects. Classes are objects too.
The evidence is that you can do the same things with a class that you do with any other value. The next example binds a second name to a class, stores classes in a dictionary, and uses the dictionary as a lookup table.
class Dog:
sound = "woof"
class Cat:
sound = "meow"
Animal = Dog # a second name for the same class object
print(Animal is Dog) # True
print(Animal().sound) # woof
registry = {"dog": Dog, "cat": Cat}
def make(kind):
cls = registry[kind] # look up a class like any other value
return cls() # call it to get an instance
print(type(make("cat")).__name__) # CatThe class statement does two things. It creates a class object and it binds that object to a name. Nothing special ties the object to the name Dog. Animal and Dog are two references to one object, exactly as with two names for one list.
Every object has a type
The built-in type() function, called with one argument, returns the class of an object.
print(type(3)) # <class 'int'>
print(type("hi")) # <class 'str'>
print(type([1, 2])) # <class 'list'>
print(type(Dog())) # <class '__main__.Dog'>The result is always a class object, and you can compare it with another class using is.
Because type() returns a class and classes are objects, you can ask the same question about a class.
print(type(Dog)) # <class 'type'>
print(type(int)) # <class 'type'>
print(type(type)) # <class 'type'>The class of Dog is type. The class of int is type. The class of type is type itself. The built-in type is the class that classes are instances of. Anything that serves as the class of a class is called a metaclass, so type is the default metaclass.
The next diagram shows the chain.
Read each arrow as "is an instance of". The instance d is an instance of Dog. Dog is an instance of type. type is an instance of itself, which is how the chain ends.
Two relationships that are easy to confuse
Python has two separate relationships between classes, and mixing them up is the most common source of confusion in this topic.
- Instance of means "was created by calling this class". It is reported by
type(obj)and tested byisinstance. - Subclass of means "inherits from this class". It is listed in
__bases__and tested byissubclass.
Here is how they apply to object and type.
print(isinstance(Dog, type)) # True: Dog was created by type
print(issubclass(Dog, object)) # True: Dog inherits from object
print(isinstance(Dog, object)) # True: every class is also an object
print(issubclass(type, object)) # True: type inherits from object
print(isinstance(object, type)) # True: object is itself a class
print(Dog.__bases__) # (<class 'object'>,)
print(Dog.__mro__) # (<class '__main__.Dog'>, <class 'object'>)The two relationships point in different directions. Dog inherits behavior from object, and Dog is built by type. A metaclass changes the second relationship. A parent class changes the first. You will use the first to change how a class is built and the second to change what its instances can do.
| Question | How to ask it | For `Dog` |
|---|---|---|
| What built this class? | `type(Dog)` | `type` |
| What does it inherit from? | `Dog.__bases__` | `(object,)` |
| In what order are attributes searched? | `Dog.__mro__` | `(Dog, object)` |
| What is its name? | `Dog.__name__` | `'Dog'` |
What a class object holds
A class object carries data about itself. A few attributes are worth knowing now because later chapters rely on them.
class Dog:
sound = "woof"
def speak(self):
return self.sound
print(Dog.__name__) # Dog
print(Dog.__qualname__) # Dog
print(Dog.__module__) # __main__
print(sorted(k for k in Dog.__dict__ if not k.startswith("__")))
# ['sound', 'speak']
print(type(Dog.__dict__)) # <class 'mappingproxy'>The __dict__ of a class holds the names defined in its body: the data attributes and the functions. It is a mappingproxy, a read-only view. You can read from it, but you cannot assign into it.
try:
Dog.__dict__["legs"] = 4
except TypeError as exc:
print(exc) # 'mappingproxy' object does not support item assignmentTo add an attribute to a class you use normal attribute assignment. The class then handles the change itself.
Dog.legs = 4
print(Dog().legs) # 4Python lets you do this because a class is a mutable object. Assigning Dog.legs is just as legitimate as assigning an attribute on any other object.
Changing a class affects existing instances
Instances do not copy a class's attributes. When you look up obj.name, Python checks the instance first, then the class, then the parent classes in method resolution order. As a result, a change to the class is visible through instances that already exist.
class Counter:
count = 0
a = Counter()
b = Counter()
Counter.count = 5
print(a.count, b.count) # 5 5
a.count = 1 # creates an instance attribute
print(a.count, b.count, Counter.count) # 1 5 5The assignment a.count = 1 does not modify the class. It creates a new entry in the instance's own dictionary, and that entry hides the class attribute for a only. This lookup rule matters later, because a class decorator or hook that changes a class after creation instantly changes what every instance sees.
Classes created at runtime
A class statement is executable code. It runs when the interpreter reaches it, not when the file is parsed. That means a class can be defined inside a function, inside an if branch, or inside a loop.
def make_class(greeting):
class Greeter:
def hello(self):
return greeting
return Greeter
A = make_class("hi")
B = make_class("yo")
print(A is B) # False
print(A().hello(), B().hello()) # hi yo
print(A.__name__ == B.__name__) # True
print(A.__qualname__) # make_class.<locals>.Greeter
print(isinstance(A(), B)) # FalseEach call to make_class runs the class statement again and produces a new, separate class object. A and B share the name Greeter but are different objects. Python compares classes by identity, not by name, so an instance of A is not an instance of B.
This is the practical meaning of "classes are objects". A function can build and return a class, and the resulting objects behave like any others. The next chapter shows how type() lets you do this without writing a class statement at all.
Common errors
These mistakes come from forgetting that a class is an object.
- Calling a class when you meant to refer to it.
registry = {"dog": Dog()}stores one instance.registry = {"dog": Dog}stores the class. Use the second form when you want to create instances later. - Assuming
type(x) == Dogis the same asisinstance(x, Dog). The first is true only for exact instances ofDog. The second also accepts instances of subclasses. Preferisinstanceunless you need the exact type. - Writing into
__dict__. Class__dict__is read-only. Usesetattr(cls, name, value)or plain attribute assignment. - Expecting a name to identify a class. Compare classes with
is, never by__name__. - Treating
typeas only a function. With one argument it reports a class. With three arguments it creates one. Both uses are covered in the next chapter.
Summary of the model
- A class is an object. You can bind it, pass it, store it and modify it.
- The class of an instance is found with
type(obj). - The class of a class is, by default,
type. A different class of a class is called a metaclass. - "Instance of" and "subclass of" are separate relationships. Metaclasses affect the first and inheritance affects the second.
- A
classstatement runs at runtime, so each execution creates a new class object.
Exercise
Given class Dog: pass and d = Dog(), what do type(d), type(Dog) and type(type(Dog)) return? Which of the three results is the metaclass of Dog?
Show answer
type(d) returns Dog. type(Dog) returns type. type(type(Dog)) also returns type. The metaclass of Dog is the second result, type, because it is the class of the class object Dog.
Exercise
What does this code print, and why? def build(): class Item: pass return Item X = build() Y = build() print(X is Y, X._name == Y.name_, isinstance(X(), Y))
Show answer
It prints False True False. Each call to build() runs the class statement again and creates a new class object, so X is Y is False. Both classes are named Item, so the name comparison is True. An instance of X is not an instance of Y because Python compares classes by identity, so isinstance is False.