Sub topic 1
What classes and objects are
A class describes a kind of thing: what data it holds and what it can do. An object is one concrete thing of that kind. This chapter covers the vocabulary, what happens when Python runs a class statement, and what happens when you call a class to get an instance. Later chapters cover initializers, attributes, and methods in detail.
Prerequisites
This chapter assumes you can:
- Write and call Python functions with arguments and return values.
- Use built-in types such as strings, lists, and dictionaries.
- Read basic control flow (
if,for,while). - Run Python 3 code from a script or the REPL (the interactive prompt).
You do not need to know anything about classes yet.
Why classes exist
Suppose you track dogs with dictionaries:
dog1 = {"name": "Rex", "age": 3}
dog2 = {"name": "Fido", "age": 5}
def describe(dog):
return f"{dog['name']} is {dog['age']} years old"
print(describe(dog1))This works, but nothing ties the data to the function. A dictionary with a misspelled key ("nmae") is still a valid dictionary. describe will accept any dictionary, including one that has nothing to do with dogs.
A class bundles three things:
- A name for the kind of thing (
Dog). - The data each thing carries (state).
- The functions that work on that data (behavior).
Python then gives you a new type. You can ask whether a value is a Dog, create as many dogs as you need, and put behavior in one place.
Defining a class and creating instances
The smallest useful class has a name and an empty body:
class Dog:
pass
rex = Dog()
fido = Dog()
print(type(rex)) # <class '__main__.Dog'>
print(isinstance(rex, Dog)) # True
print(rex is fido) # FalseHere is the vocabulary:
- Class: the definition, created by the
classstatement.Dogis a class. - Instance: one object created from a class.
rexandfidoare instances ofDog. The words "instance" and "object" are close to synonyms. "Instance ofDog" says which class the object belongs to. - Instantiation: creating an instance by calling the class like a function,
Dog().
The parentheses matter. rex = Dog does not create a dog. It gives the class a second name. rex = Dog() calls the class and returns a new instance.
Each call to Dog() returns a distinct object. rex is fido is False because is compares identity, meaning whether two names refer to the same object. Two instances built the same way are still two objects.
Identity, type, and value
Every object has three basic properties:
| Property | How to inspect it | Meaning |
|---|---|---|
| Identity | `id(obj)`, `a is b` | Which specific object it is. It never changes during the object's life. |
| Type | `type(obj)`, `isinstance(obj, cls)` | Which class created it. |
| Value | Depends on the type | The data it holds. Mutable objects can change it. |
Two names can refer to one object. This is the part that surprises people coming from a language with value-copying assignment:
class Dog:
pass
rex = Dog()
alias = rex # no new dog: a second name for the same object
alias.name = "Rex"
print(rex.name) # Rex
print(alias is rex) # TrueAssignment never copies an object in Python. It attaches a name to an object. When we later write methods that change self, every name bound to that instance sees the change.
Instances hold their own data
An instance has its own storage for attributes (named values attached to an object). You can add attributes to an instance by assigning to them:
class Dog:
pass
rex = Dog()
fido = Dog()
rex.name = "Rex"
fido.name = "Fido"
print(rex.name, fido.name) # Rex Fido
print(rex.__dict__) # {'name': 'Rex'}__dict__ is a regular dictionary that stores the instance's attributes. Each instance has its own, so setting rex.name does not affect fido.
Creating attributes one at a time like this is fragile. A third dog could be created with no name at all, and reading .name would raise AttributeError. The next chapter solves this with __init__, which sets up every new instance in a consistent way.
What the `class` statement does
class is an executable statement, not a declaration. When Python reaches it, it runs the indented body from top to bottom and then binds the result to the class name.
class Report:
print("class body is running")
title = "Monthly"
print(Report.title)The output is:
class body is running
MonthlyThe print in the body runs once, when the class is defined, not when instances are created. Names assigned in the body (title) become attributes of the class. Functions defined in the body become the class's methods, which a later chapter covers.
Because class is an ordinary statement, it can appear inside a function or an if block. That is rarely needed, but it shows that classes are created at run time.
Classes are objects too
In Python, a class is itself an object. You can store it in a variable, pass it to a function, and return it from one:
class Dog:
pass
def build(cls):
return cls()
pet = build(Dog) # same as Dog()
print(type(pet).__name__) # Dog
print(type(Dog)) # <class 'type'>
print(type(3), type("hi"), type([1, 2]))
# <class 'int'> <class 'str'> <class 'list'>Two facts follow from this:
- Built-in types are classes.
3is an instance ofint,"hi"is an instance ofstr, and[1, 2]is an instance oflist. When you defineDog, you are making a type that works the same way as these. - A class is an instance of
type.type(Dog)istype, sotypeis the class that builds classes. You rarely need this directly, but it explains whyDog(...)looks like any other call: calling an object is how Python creates instances.
Passing classes around is useful. A function can accept a class and build objects from it without knowing in advance which class it is, as build does above.
How an instance finds an attribute
When you write rex.legs, Python looks in the instance's __dict__ first. If the name is not there, it looks in the class. If it is not there either, it raises AttributeError.
class Dog:
pass
rex = Dog()
Dog.legs = 4 # attribute on the class
print(rex.legs) # 4 (found on the class)
print("legs" in rex.__dict__) # False
rex.legs = 3 # now the instance has its own value
print(rex.legs) # 3
print(Dog.legs) # 4 (the class is unchanged)This two-step lookup (instance, then class) is the basis of everything in the next several chapters. It explains shared class attributes, method calls, and inheritance.
Checking types: `type()` vs `isinstance()`
Two tools answer "what is this object?":
class Animal:
pass
class Dog(Animal):
pass
rex = Dog()
print(type(rex) is Dog) # True
print(type(rex) is Animal) # False
print(isinstance(rex, Dog)) # True
print(isinstance(rex, Animal)) # Truetype(rex) is Dog checks for exactly that class. isinstance(rex, Animal) is also true for instances of subclasses, which are classes that extend another class. Prefer isinstance for ordinary checks, because it keeps working when someone passes a subclass. Reserve type(x) is C for the rare case where you need the exact class. Subclassing itself is covered in the inheritance chapter. The example is here only so the difference is visible.
Common errors
- Calling without parentheses.
Dogis the class,Dog()is an instance. Printing a class shows<class '__main__.Dog'>. Printing an instance shows something like<__main__.Dog object at 0x...>. - Expecting equal-looking instances to be equal. By default
Dog() == Dog()isFalse, because equality falls back to identity. A later chapter shows how to define value-based equality. - Assuming assignment copies.
b = amakes two names for one object. Usecopyor build a new instance when you need an independent one. - Reading an attribute that was never set. Python raises
AttributeError: 'Dog' object has no attribute 'name'. Setting every attribute in__init__prevents this. - Treating
classas a declaration. The body runs immediately, so a slow or failing statement in a class body fails at import time.
Exercise
You run a = Dog(), b = a, then b.name = "Rex". What does a.name return, and how many Dog instances exist?
Show answer
a.name returns "Rex". Only one Dog instance exists. b = a binds a second name to the same object, so it does not copy anything, and the attribute set through b is visible through a.
Exercise
Given class Cat: pass and Cat.lives = 9, followed by tom = Cat() and tom.lives = 7, what do tom.lives, Cat.lives, and Cat().lives return? Which of these lookups finds the value in the instance's __dict__?
Show answer
tom.lives is 7, Cat.lives is 9, and Cat().lives is 9. Only the tom.lives lookup finds its value in the instance's __dict__. The new Cat() instance has an empty __dict__, so Python falls back to the class attribute.
Exercise
What is printed by the following code, and why does the first line appear only once? class Report: print("defining") r1 = Report() r2 = Report()
Show answer
It prints "defining" exactly once. The class body runs a single time when the class statement executes. Creating instances with Report() does not re-run the body.