Objects: Data That Knows What to Do
Since Chapter 2 you have been calling methods: text.upper(), todo.append("milk"), phones.get("Anna"). Each time, you asked a value to do something. That is because every value in Python is an object: some data, bundled together with the actions that make sense for it. A class is how you define your own kind of object, and a simple one takes only a few lines.
Think of a cookie cutter and the cookies it makes. The class is the cutter: it defines the shape. Each object made from it is a cookie: the same shape, but each can have its own icing. You can make as many cookies as you like from one cutter.
You Have Used Objects All Along
Ask any value its type and Python answers with the word class: a string is of class str, a list of class list. The methods you call on them are defined in those classes. When you write "hello".upper(), the string object runs the upper method that the str class defines.
>>> type("hello")
<class 'str'>
>>> "hello".upper()
'HELLO'
>>> type([1, 2])
<class 'list'>
class and __init__
A class is defined with the word class, a name, which by convention starts with a capital letter, and a colon. Inside it, a function called __init__, with two underscores on each side, runs whenever a new object is created, and sets up that object's data. The class below describes a simple bank account with an owner and a balance.
Creating an object looks like calling a function: Account("Anna", 100) makes a new account, runs __init__ with those values, and hands the new object back. Each object keeps its own data, reached with a dot: anna.balance.
class Account: def __init__(self, owner, balance): self.owner = owner self.balance = balance anna = Account("Anna", 100) omar = Account("Omar", 250) print(anna.owner, anna.balance) print(omar.owner, omar.balance)
Anna 100 Omar 250
self
Every function inside a class receives, as its first parameter, the particular object it is working on. By universal convention that parameter is called self. In __init__, self.balance = balance means: store this value as this particular account's balance. You never pass self yourself; Python fills it in. When you write anna.deposit(50), Python calls the method with self pointing at Anna's account.
Methods
A function defined inside a class is a method. The version below adds a deposit method that changes the account's balance. Because each object has its own data, depositing into Anna's account leaves Omar's untouched. And because the rule for depositing lives in one place, inside the class, every account follows it.
class Account: def __init__(self, owner, balance): self.owner = owner self.balance = balance def deposit(self, amount): """Add money to this account.""" self.balance = self.balance + amount anna = Account("Anna", 100) omar = Account("Omar", 250) anna.deposit(50) print(anna.balance) print(omar.balance)
150 250
A Readable Printout
Print an object of your own class and, by default, Python shows only its class and a memory address, which tells you almost nothing. The number at the end is different on every run.
<__main__.Account object at 0x10315c830>
A method called __repr__ decides what the printout looks like. Written by hand, it returns a string describing the object. The next topic shows a way to get a good one without writing it at all.
class Account: def __init__(self, owner, balance): self.owner = owner self.balance = balance def __repr__(self): return f"Account(owner={self.owner!r}, balance={self.balance})" print(Account("Anna", 100))
Account(owner='Anna', balance=100)
The !r inside the braces asks the f-string for the value's repr, the version with quotes, which is how the printout shows that the owner is text.
- "I have to pass self when calling a method." Python passes it for you. You write it only in the method's definition.
- "A class is an object I can use directly." A class is the blueprint; you use it to make objects. (Strictly, a class is itself an object in Python, but that detail does not matter here.)
- "Real programs need classes for everything." Classes are one tool among several. The last topic of this chapter says when they help and when they do not.
- Reading other people's Python means reading classes. After this page they are no longer mysterious.
- Keeping data together with the operations that belong to it puts each rule in one place, where it cannot be forgotten.
Knowledge Check
What does self refer to inside a method?
- The particular object the method was called on
- The class itself, which is shared by every object made
- The first argument the caller typed in the brackets
- The function that is currently running
When does __init__ run?
- Once, when the class is first defined
- Each time a new object is made from the class
- Every time any method of the object is called
- Only when the object is printed to the terminal
After anna.deposit(50), what happens to Omar's account?
- It also gains 50, because both use the same class
- It is reset, because deposit changes the class
- Nothing: only Anna's balance changes
- It raises an error, because only one object may change
What is __repr__ for?
- It creates a new object from the class
- It removes an object when it is no longer needed
- It checks that all of the object's data is valid
- It decides how the object looks when printed
You got correct