Python Classes and Objects · Lesson 81 of 149

Python Classes and Objects

What you will learn

  • What a class and an object (instance) are
  • How to define a class and create objects
  • What __init__ and self do
  • Attributes and methods
  • That each object has its own data
  • The first errors to recognise

1. Why classes?

So far, you have kept related data together in a dictionary or a tuple, and you have written separate functions to work on it. A class goes further: it bundles data and the functions that work on it into one unit. This style is called object-oriented programming.

Everything in Python is already an object. A string, a list and a dictionary each carry their own data and have their own methods ("abc".upper(), [1, 2].append(3)). With classes, you can build your own kinds of objects: a bank account, a game character, a shape.

Word Meaning Real-world picture
class a blueprint that says what data and actions a kind of object has the design of a house
object (also instance) one thing made from the blueprint, with its own data one actual house

You can build many objects from one class, as many houses from one design.

2. Your first class

A class is defined with the word class, a name and a colon, and an indented body. Class names use CapWords (each word starts with a capital letter):

class Dog:
    def __init__(self, name, age):
        self.name = name
        self.age = age

    def bark(self):
        return f"{self.name} says woof"

    def birthday(self):
        self.age += 1

Then you create objects by calling the class like a function:

rex = Dog("Rex", 3)
fido = Dog("Fido", 5)
print(rex.name, rex.age)
print(rex.bark())
print(fido.bark())
Rex 3
Rex says woof
Fido says woof
  • Dog("Rex", 3) creates one object and gives it to rex.
  • rex.name reads an attribute (a piece of data stored in the object).
  • rex.bark() calls a method (a function that belongs to the object).
Quick check: how many Dog objects does the code above create?

Two: rex and fido, each with its own name and age.

3. init: setting up a new object

__init__ is a special method that Python calls automatically when a new object is created. It is the initialiser: its job is to give the new object its starting data. Whatever you pass in the brackets of Dog(...) is handed to __init__:

rex = Dog("Rex", 3)

is like saying: make a new empty Dog, then run __init__(that_dog, "Rex", 3).

Inside __init__, you write self.name = name to store the value on the object. The double underscores before and after the name mark it as one of Python's special methods (lesson 13.7).

An __init__ should set up every attribute the object will need, so that no method is ever surprised by a missing one.

4. self: the object itself

Every method has self as its first parameter. It is the object the method is called on:

rex.bark()

Python quietly turns that into Dog.bark(rex): the object before the dot becomes self. That is why self.name inside bark means this dog's name:

print(rex.bark())
print(fido.bark())
print(Dog.bark(rex))
Rex says woof
Fido says woof
Rex says woof
  • self is not a keyword: it is an ordinary name that everybody uses by convention. Always use self.
  • You do not pass self when you call the method; Python supplies it.
  • Inside the class, you reach an object's data through self.: self.age += 1.
rex.birthday()
print(rex.age, fido.age)
4 5

birthday changed Rex's age only. Each object has its own attributes.

5. Each object has its own data

An object's attributes are stored in the object, as a dictionary named __dict__:

print(rex.__dict__)
print(fido.__dict__)
{'name': 'Rex', 'age': 4}
{'name': 'Fido', 'age': 5}

You can add an attribute to one object, even if the class did not mention it, although that is usually a bad idea (set everything up in __init__):

rex.color = "brown"
print(rex.color, hasattr(rex, "color"), hasattr(fido, "color"))
print(getattr(fido, "color", "none"))
brown True False
none
  • hasattr(obj, "name") tests whether the object has an attribute.
  • getattr(obj, "name", default) reads it, with a default.
  • del rex.color removes it again.

A name used before it has been set is an error:

fido.color
AttributeError: 'Dog' object has no attribute 'color'

6. Methods

A method is a function defined inside a class, with self first. Methods can:

  • read the data: return f"{self.name} says woof"
  • change the data: self.age += 1
  • take more arguments and return values, like any function (chapter 11)
  • call other methods with self.other_method()
class Rectangle:
    def __init__(self, width, height):
        self.width = width
        self.height = height

    def area(self):
        return self.width * self.height

    def perimeter(self):
        return 2 * (self.width + self.height)

    def scale(self, k):
        self.width *= k
        self.height *= k
        return self

r = Rectangle(3, 4)
print(r.area(), r.perimeter())
print(r.scale(2).area())
print(r.width)
12 14
48
6
  • scale changes the object, and returns self, so you can chain calls: r.scale(2).area().
  • After scaling, the width is 6: the object itself was changed.

7. Objects are independent, but names can be shared

Each object made by a class is separate:

class Counter:
    def __init__(self):
        self.count = 0

    def hit(self):
        self.count += 1
        return self.count

c1 = Counter()
c2 = Counter()
c1.hit()
c1.hit()
c2.hit()
print(c1.count, c2.count)
2 1

But, as with lists, a second name for the same object is not a copy (lesson 2.7):

alias = c1
alias.hit()
print(c1.count, alias is c1)
3 True

Objects are mutable by default: you can change their attributes after they are made.

8. Defaults and flexible creation

__init__ is a normal function, so it can have default values, keyword arguments and so on (chapter 11):

class Point:
    def __init__(self, x=0, y=0):
        self.x = x
        self.y = y

p = Point()
q = Point(3, 4)
print(p.x, p.y, q.x, q.y)
print((q.x ** 2 + q.y ** 2) ** 0.5)
0 0 3 4
5.0

9. Looking at objects

print(type(rex), type(rex).__name__)
print(isinstance(rex, Dog), isinstance(rex, object), isinstance("x", Dog))
print(rex)
<class '__main__.Dog'> Dog
True True False
<__main__.Dog object at 0x000001D2A9B16A50>
  • type(rex) is the class, and isinstance(rex, Dog) is the standard test. Every object is an instance of object.
  • Printing an object gives a plain default that shows the class and a memory address (which differs each time). Lesson 13.7 shows how to give your own objects a nice printed form.
  • A class is itself an object: type(Dog) is type.

By default, two different objects are never equal, even with the same data:

print(Dog("Rex", 4) == Dog("Rex", 4))
print(rex == rex)
False
True

== compares identity unless the class says otherwise (lesson 13.8).

10. The first errors

Mistake Error
forgetting an argument TypeError: Dog.__init__() missing 1 required positional argument: 'age'
forgetting self in a method definition TypeError: Bad.speak() takes 0 positional arguments but 1 was given
using an attribute that was never set AttributeError: 'Dog' object has no attribute 'color'
writing name instead of self.name inside a method NameError, or the wrong variable

The second one is very common. In def speak(): the self is missing, but Python still passes the object, so you get "takes 0 positional arguments but 1 was given".

Worked example: a bank account

Write a class for a bank account with a name, a balance, deposit, withdraw and a method that reports the balance. Use it for two accounts.

class Account:
    def __init__(self, owner, balance=0):
        self.owner = owner
        self.balance = balance

    def deposit(self, amount):
        self.balance += amount
        return self.balance

    def withdraw(self, amount):
        if amount > self.balance:
            raise ValueError("insufficient funds")
        self.balance -= amount
        return self.balance

    def report(self):
        return f"{self.owner}: {self.balance}"

a = Account("Rina", 100)
b = Account("Sam")
a.deposit(50)
b.deposit(20)
a.withdraw(30)
print(a.report())
print(b.report())

try:
    b.withdraw(500)
except ValueError as e:
    print("ValueError:", e)

print(a.balance, b.balance)
Rina: 120
Sam: 20
ValueError: insufficient funds
120 20
Part Role
__init__(self, owner, balance=0) sets the starting data; balance defaults to 0
deposit, withdraw change the object's data, with a rule (no overdraft)
report reads the data
two objects a and b each has its own balance

This is the closure bank from lesson 11.10, written as a class: the data is now visible as attributes, and it is easy to add more methods. The names and amounts are made up. (Raising ValueError is covered in chapter 14.)

Common mistakes

  • Forgetting self as the first parameter of a method.
  • Writing name = name instead of self.name = name in __init__: nothing is stored on the object.
  • Calling a method without brackets (rex.bark is the method, rex.bark() runs it).
  • Setting attributes outside __init__ so that other methods find them missing.
  • Expecting two objects with the same data to be equal.
  • Thinking b = a makes a copy of an object.

Key takeaways

  • A class is a blueprint; an object (instance) is one thing made from it, created by calling the class: Dog("Rex", 3).
  • __init__ runs automatically for a new object and sets its starting attributes; self is the object the method works on.
  • Attributes (self.name) hold each object's own data; methods are functions defined in the class.
  • Objects are independent, mutable, and compare by identity by default.
  • Set up every attribute in __init__; always put self first in a method.

Practice

1. Write a class Cat whose objects have a name and a method meow() that returns "<name> says meow".

Show answer
class Cat:
    def __init__(self, name):
        self.name = name

    def meow(self):
        return f"{self.name} says meow"

2. What does self mean in a method?

Show answer

The object that the method was called on. rex.bark() runs bark with self equal to rex.

3. What error does Dog("Rex") give if __init__ needs a name and an age?

Show answer

TypeError: Dog.__init__() missing 1 required positional argument: 'age'.

4. After a = Counter() and b = a, then b.hit(), what is a.count?

Show answer

1. Both names refer to the same object.

5. Why is Point(1, 2) == Point(1, 2) false by default?

Show answer

Equality compares identity unless the class defines otherwise; two separate objects are different objects (lesson 13.8 shows how to change this).

6. Add a method is_adult to a Person class with an age attribute, returning True from 18.

Show answer
def is_adult(self):
    return self.age >= 18