Intermediate   Chapter 118 · 25 min read · Module 10: Object-Oriented Programming

Classes and Objects

Learning objectives
  • After this chapter you can explain the difference between a class and an object.
  • You can define a class with the class keyword and create objects from it.
  • You can give an object attributes and read or change them with dot notation.
  • You can add a simple method to a class and call it on an object.
  • You can explain that each object is separate and that two names can point to one object.

Up to now you have used values such as numbers, strings and lists. Each of these is an object that Python created for you. In this chapter you learn to design your own kinds of objects. You do this by writing a class, which is a plan that tells Python what a new kind of object looks like and what it can do.

Think of a house plan. The plan is not a house, but you can build many houses from it. Each house has its own colour and its own people, even though all of them follow the same plan. A class works the same way, and every object built from it is called an instance.

In this chapter you will write your first classes, create objects, store data inside them and call small methods. The next chapters will build on this, so take your time and run each example yourself.

What is a class?

A class is a blueprint for creating objects. It groups data and the functions that work on that data in one place. You create a class with the class keyword, followed by a name and a colon. By convention class names use CapitalizedWords, such as Dog or BankAccount, so that they are easy to tell apart from variables.

Object: a value created from a class that holds its own data (attributes) and can use the behaviour (methods) the class defines

The simplest class has nothing inside it. We write the word pass as a placeholder because Python needs at least one statement in an indented block. Even an empty class is useful, because you can already create objects from it and attach data to them.

Example 1: an empty class and two objects
class Dog:
    pass

a = Dog()
b = Dog()
print(type(a))
print(a is b)
print(isinstance(a, Dog))
<class '__main__.Dog'> False True

Calling the class like a function, Dog(), creates a new object. We say we instantiate the class. The two objects a and b are different objects even though they come from the same class, so a is b is False. The built-in isinstance checks whether an object was made from a given class.

Attributes: data stored in an object

An attribute is a variable that belongs to an object. You create or change it with dot notation: write the object, a dot, and the attribute name. Every object keeps its own attributes, so changing one dog does not change another dog.

Example 2: attributes with dot notation
class Dog:
    pass

rex = Dog()
rex.name = "Rex"
rex.age = 3

bella = Dog()
bella.name = "Bella"
bella.age = 5

print(rex.name, rex.age)
print(bella.name, bella.age)
rex.age = rex.age + 1
print(rex.age, bella.age)
Rex 3 Bella 5 4 5

Setting attributes one by one after creating the object works, but it is easy to forget one. In real programs we usually set the starting attributes inside a special method called the constructor. You will study it in the next chapter. For now it is enough to know that attributes can be added at any time.

Methods: behaviour of an object

A method is a function defined inside a class. Its first parameter is always named self, and Python fills it in automatically with the object you call the method on. Through self the method can read and change the attributes of that particular object.

Example 3: a class with a method
class Dog:
    def speak(self):
        return self.name + " says woof"

rex = Dog()
rex.name = "Rex"
print(rex.speak())

bella = Dog()
bella.name = "Bella"
print(bella.speak())
Rex says woof Bella says woof

When you write rex.speak(), Python turns it into Dog.speak(rex). That is why the method gets self without you passing it. We will look at self more closely in a later chapter.

Objects are separate, names are not

Two variables can point to the same object. Assigning one variable to another does not copy the object, it only gives it a second name. If you change the object through one name, you see the change through the other. To get a separate object, you must create a new one with the class call.

Example 4: two names, one object
class Counter:
    pass

c1 = Counter()
c1.count = 0
c2 = c1
c2.count += 5
print(c1.count)
print(c1 is c2)

c3 = Counter()
c3.count = 0
print(c3.count, c1.count)
5 True 0 5
TermMeaningExample
ClassThe blueprintclass Dog:
Object / instanceOne thing built from the blueprintrex = Dog()
AttributeData stored in an objectrex.name
MethodFunction defined in a classrex.speak()
Use type(obj) to see which class an object belongs to, and vars(obj) to see its attributes as a dictionary. Both are very helpful when you are learning.

Why use classes?

Classes let you model real things in your program. A game can have Player and Enemy classes, a shop can have Product and Order classes. Keeping data and behaviour together makes code easier to read, test and reuse. When a program grows, this organisation saves a lot of time because every idea has one clear home.

Python syntax

Syntax
class ClassName:
    def method_name(self):
        ...
Syntax
obj = ClassName()
obj.attribute = value
obj.method_name()

Real-world applications

  • Modelling students, books or products in a school or shop program.
  • Game characters that each keep their own health and position.
  • Bank accounts that each hold their own balance.
  • Representing items in a to-do list or inventory app.

Common mistakes

Mistake: Writing rex = Dog without brackets and expecting an object.
Fix: Call the class with brackets, Dog(), to create an instance. Without them you only refer to the class itself.
Mistake: Forgetting self as the first parameter of a method.
Fix: Always write def method(self):. Without it Python raises a TypeError about the number of arguments.
Mistake: Reading an attribute that was never set, such as rex.colour.
Fix: Set the attribute first, or set all attributes in the constructor so every object has them.
Mistake: Thinking b = a copies the object.
Fix: It only creates a second name. Create a new object with Dog() when you need a separate one.

Important tips

  • Start class names with a capital letter and use lowercase for variables and methods.
  • Use type(), isinstance() and vars() to inspect objects while debugging.
  • Keep a class focused on one idea so it stays easy to understand.

Key points summary

  • A class is a blueprint, an object is a thing built from it.
  • Calling ClassName() creates a new instance.
  • Attributes hold data, methods hold behaviour.
  • Each object has its own attributes.
  • Assignment copies the reference, not the object.

Exam and interview points

  • Define class, object, instance, attribute and method.
  • ClassName() creates an instance; type(obj) returns its class.
  • Methods take self as the first parameter.
  • b = a makes both names refer to the same object.

Quick revision

  • class Name: defines a blueprint.
  • Name() creates an object.
  • obj.attr = value stores data.
  • obj.method() calls behaviour.
  • Two names can share one object.

Frequently asked questions

What is the difference between a class and an object?

A class is the plan and an object is one thing made from the plan. You write one class and can create as many objects from it as you need.

Do I always need `pass` in an empty class?

You need some statement in the indented block. `pass` does nothing, so it is the usual placeholder. A docstring would also work.

Why is the first parameter called self?

It is only a convention, but everyone follows it. Python passes the object itself as the first argument, and self is the name that refers to it.

Can I add attributes to an object after creating it?

Yes, in normal classes you can. It is better practice to set them in the constructor so all objects have the same attributes.

Is everything in Python an object?

Yes. Numbers, strings, lists, functions and even classes are objects, which is why you can use dot notation on so many things.

Practise this chapter

19 practice questions Take the chapter quiz

Related chapters