Sub topic 1
What Classes and Objects Are
A class is a blueprint that defines a new type. An object, also called an instance, is a value built from that blueprint. This chapter gives you the working model. Later chapters cover initializers, attributes, methods, and inheritance in detail.
Prerequisites
This chapter assumes you can:
- Write Python functions with arguments and return values.
- Use built-in types such as strings, lists, and dictionaries.
- Use basic control flow (
if,for,while). - Run Python 3 code from a script or the REPL.
Classes define types
You already use classes. The value "hello" is an instance of str, and [1, 2] is an instance of list. Each type bundles data with the functions that work on that data. A class statement lets you define your own type in the same way.
class Dog:
pass
rex = Dog()
fido = Dog()
print(type(rex)) # <class '__main__.Dog'>
print(isinstance(rex, Dog)) # True
print(rex is fido) # FalseCalling the class, Dog(), creates a new instance. Each call produces a separate object with its own identity, so rex is fido is False. The name Dog is an ordinary variable that refers to the class object. Classes are themselves objects in Python.
Objects hold their own state
An instance has its own namespace, which is a dictionary of attribute names and values. You can add attributes to it by assignment.
class Dog:
pass
rex = Dog()
rex.name = "Rex"
rex.age = 3
fido = Dog()
fido.name = "Fido"
print(rex.name, rex.age) # Rex 3
print(fido.name) # Fido
print(rex.__dict__) # {'name': 'Rex', 'age': 3}Changing rex does not affect fido. That separation is the main reason to use objects: each one carries its own state.
Adding attributes after creation works, but it is fragile. Nothing guarantees every Dog has a name, so fido.age raises AttributeError. The next chapter fixes this with __init__, which sets up every instance the same way.
Putting behavior in the class
Functions defined inside a class body are stored on the class, not on each instance. Python looks them up when you use the dot syntax.
class Dog:
def bark(self):
return "Woof"
rex = Dog()
print(rex.bark()) # Woof
print(Dog.bark(rex)) # Woof, the same call written outThe two calls are equivalent. When you write rex.bark(), Python finds bark on the class and passes rex as the first argument. By convention that parameter is named self. Chapter 2 covers self in detail.
How attribute lookup works
When you read rex.something, Python checks the instance's own namespace first. If the name is not there, it checks the class. This is why methods, which live on the class, are visible from every instance.
Inheritance adds more places to search, which a later chapter covers.
Common mistakes
- Forgetting the parentheses.
rex = Dogmakesrexanother name for the class, not an instance. WriteDog(). - Confusing the class with its instances.
Dog.nameandrex.nameare different lookups. - Assuming every instance has the same attributes. Without an initializer, they can differ.
Exercise
Given class Cat: pass, a = Cat(), and b = Cat(), you run a.lives = 9. What does b.lives do, and why?
Show answer
It raises AttributeError. The attribute was stored in the namespace of a only. b has its own namespace, and Cat has no lives attribute, so the lookup fails in both places.
Exercise
What does Dog.bark(rex) do differently from rex.bark()?
Show answer
Nothing. Both call the same function with rex as self. The rex.bark() form is shorthand where Python supplies the instance for you.