livepython.net
CHAPTER 20Object-Oriented Programming (Classes)
20.1  CLASSES

Python Classes and Objects for Beginners

What Are Classes and Objects in Python?

A class is a blueprint: a plan that says what a kind of thing has and what it can do. An object is one real thing built from that blueprint. Writing programs around classes and objects is called object-oriented programming, or OOP for short.

Think of it like a cookie cutter. The cutter is the class: it gives every cookie the same shape. Each cookie you press out is an object. They all share the shape, but each one is its own cookie, and you can put different icing on each.

IdeaReal lifePython
Classthe blueprint of a houseclass Dog:
Objectone house built from itrocky = Dog()
  • One class can make as many objects as you like.
  • Every object made from a class has the same parts, but its own values: Rocky and Lucky are both dogs, with different names.
  • An object keeps data (what it has, like a name) and actions (what it can do, like bark) together, in one place.

You've used objects all along

Every value in Python is an object. "sunny" is an object made from the class str. A list is an object made from the class list. And upper() and append() are actions those objects can do:

PYTHONedit me
name = "sunny"
print(name.upper())
pets = ["Rocky"]
pets.append("Lucky")
print(pets)
OUTPUT
SUNNY
['Rocky', 'Lucky']

In this chapter, you'll make your own classes, like Dog, Student and BankAccount, each with its own data and actions.

Common beginner doubt: "Do I need classes to write programs?" No. Everything you've built so far worked without them. Classes help when a program has many things of the same kind, like 30 students or 100 bank accounts, each with its own data.

A class is the blueprint; an object is one thing built from it.

your turnPick the right idea

A game has a class Car. The player builds three cars from it. How many objects are there?

Think about it, then pick one.
your turnPredict the output

Remember list methods?

pets = ["Rocky", "Lucky"] pets.append("Sunny") pets.remove("Rocky") print(pets)
Your turn! What will this code show on the screen?

Create a Class in Python

You define (create) a class with the keyword class, a name, and a colon. The indented lines under it are the class's body.

Think of it like drawing the plan of a house. Drawing the plan doesn't build a house yet. Defining a class works the same way: it only describes a kind of thing.

PYTHONedit me
class Dog:
    """A pet dog."""

print("The class is ready.")
OUTPUT
The class is ready.

Only the last line printed. Defining a class makes the blueprint. It doesn't make any dogs.

The parts

  1. class, the keyword that starts a class.
  2. The name in PascalCase, as you learned in chapter 16: Dog, Student, BankAccount. Each word starts with a capital letter, with no underscores.
  3. A colon : at the end of the line, just like def and if.
  4. The body, indented by 4 spaces. For now, a docstring (chapter 15) that says what the class is for. Soon, the body will hold functions too.

A class body can't be empty. If you have nothing to put in it yet, a docstring is enough. You may also see the keyword pass, which means "do nothing here":

PYTHONedit me
class Student:
    pass

print("Done")
OUTPUT
Done

Avoid: a missing colon

PYTHONedit me
class Dog
    """A pet dog."""
OUTPUT
SyntaxError: expected ':'

Avoid: an empty body

PYTHONedit me
class Dog:

print("Done")
OUTPUT
IndentationError: expected an indented block after class definition on line 1

Don't be scared of these errors! They're old friends from def and if. Python wants a colon, then an indented body.

Common mistake: naming a class in snake_case, like class pet_dog:. Python allows it, but every Python programmer expects a class name in PascalCase: class PetDog:. Then anyone can tell at a glance that it's a class.

class, a PascalCase name, a colon, then an indented body. A class is a blueprint; it doesn't make anything yet.

your turnFill the gap

Complete the class

? Dog: """A pet dog.""" print("Ready")

It should print: Ready

Which piece makes this code work?
your turnSpot the bug

Which line breaks?

One line stops this program. Tap it.

Create Objects from a Class

To create an object, call the class like a function: its name, then brackets. Dog() builds a brand-new object from the Dog blueprint. An object is also called an instance of its class.

Think of it like a cake recipe in a cookbook. The recipe stays in the book. Every time the baker follows it, a new cake comes out of the oven.

PYTHONedit me
class Dog:
    """A pet dog."""

rocky = Dog()
lucky = Dog()
rocky.name = "Rocky"
lucky.name = "Lucky"
print(rocky.name)
print(lucky.name)
OUTPUT
Rocky
Lucky

The rules

  • Dog() makes a new object. Store it in a variable (in snake_case) to use it later.
  • Each call makes a different object: rocky and lucky are two separate dogs.
  • A dot reaches inside an object. rocky.name = "Rocky" stores a value in that object. Values stored in an object are called attributes.
  • rocky.name reads the attribute back.

Each object keeps its own attributes. Changing Sunny's cat doesn't touch Lucky's:

PYTHONedit me
class Cat:
    """A pet cat."""

sunny_cat = Cat()
sunny_cat.age = 2
lucky_cat = Cat()
lucky_cat.age = 5
sunny_cat.age = 3
print(sunny_cat.age, lucky_cat.age)
OUTPUT
3 5

Avoid: reading an attribute that isn't there

PYTHONedit me
class Dog:
    """A pet dog."""

rocky = Dog()
print(rocky.name)
OUTPUT
AttributeError: 'Dog' object has no attribute 'name'

Every error is a clue! It's saying this Dog object has no name yet: nobody stored one.

Common beginner doubt: "Do I have to add every attribute by hand, one object at a time?" You can, but it's slow and easy to forget one. In the next topic, you'll learn __init__, which gives every object its attributes the moment it's made.

Call the class, like Dog(), to make an object. Use a dot to store and read its attributes.

your turnPredict the output

What will this print?

class Pet: """A pet.""" a = Pet() b = Pet() a.name = "Rocky" b.name = "Lucky" a.name = "Sunny" print(a.name, b.name)
Your turn! What will this code show on the screen?
your turnOrder the lines

Put the lines in order to print: red

  1. class Car:
  2. my_car = Car()
  3. """A car."""
  4. print(my_car.color)
  5. my_car.color = "red"
These lines are mixed up. Put them back in order, then press Check.

Check an Object's Class with type()

Back in chapter 4, type() printed answers like <class 'int'>, and you read "class" as "type". Now you know the full story: a class is a type. type() tells you which class an object was made from, and that includes your own classes.

Think of it like the label on the bottom of a toy: "Made by Sunny Toys". Every object carries the name of the class that made it.

PYTHONedit me
class Dog:
    """A pet dog."""

rocky = Dog()
print(type(rocky))
print(type("Rocky"))
print(type(25))
OUTPUT
<class '__main__.Dog'>
<class 'str'>
<class 'int'>

Reading the answer

  • '__main__.Dog' means the class Dog, made in __main__. That's Python's name for the file you're running. Built-in classes like str don't show that part.
  • str, int, float, bool, list and dict are classes too. Python wrote them; you wrote Dog.
  • Every value you've ever used is an object of some class.

Ask a yes or no question: isinstance()

isinstance(thing, ClassName) gives True when the object was made from that class, and False when it wasn't:

PYTHONedit me
class Dog:
    """A pet dog."""

class Cat:
    """A pet cat."""

rocky = Dog()
print(isinstance(rocky, Dog))
print(isinstance(rocky, Cat))
print(isinstance("Rocky", str))
OUTPUT
True
False
True

That's handy inside an if, when a program needs to know what kind of thing it has.

Common beginner doubt: "Why does int start with a small letter, if classes use PascalCase?" Python's oldest built-in classes are older than the naming rule, as you saw in chapter 16. Your own classes always use PascalCase.

A class is a type. type() names an object's class, and isinstance() checks it.

your turnType the output

Type what this prints

class Cat: """A pet cat.""" lucky = Cat() print(type(lucky))
Read the code line by line, then type the output exactly.
your turnPick the right idea

Which one of these is a class?

Think about it, then pick one.

Practice: Classes

Solve these to lock in what you learned in this topic. Each one runs in your browser.

  1. 180.Python Program to Create a Class and an ObjectEasySolve
  2. 181.Python Program to Find the Older Pet Using ObjectsMediumSolve