Classes and OOP I

Classes and Objects

Python gives you strings, lists, and dictionaries out of the box. But what if you need to represent something those types do not cover? A class lets you define your own type. In this lesson you will create your first one.


So far, Python has given you ready-made types: strings, lists, dictionaries. But what if you need to represent something those types do not cover, like a dog, a bank account, or a player in a game?

A class lets you define your own type. Think of it as a template that describes what data something holds and what it can do. Once you have a class, you create individual objects from it.

You have actually been using classes all along. Every value in Python comes from one.

You know type() from earlier series. Look at what it tells you:

Python
Output

See the word class in each result? int, str, list are all classes that Python provides. Now you will write your own.

Use the class keyword followed by a name. Class names use PascalCase by convention:

Python

pass is a placeholder. It means the class body is empty for now. We will fill it in later lessons.

To create an object from a class, call the class name with parentheses. The result is called an instance of that class.

Here we create an instance of Dog and check its type:

Python
Output

What will be the output?

Python

Each call creates a separate object. Two instances of the same class are independent, just like two separate lists are independent even though both are lists.

Even though both come from Dog, they are not the same object:

Python
Output

You can attach data to an instance using dot notation. With a dictionary you write d["name"]. With an object you write obj.name. The stored values are called attributes.

Here we give rex a name attribute after creation:

Python
Output

What will be the output?

Python

Setting an attribute on one instance does not affect other instances. Each object keeps its own data.

isinstance() checks whether an object belongs to a given class:

Python
Output

What will be the output?

Python

What will be the output?

Python

What will be the output?

Python

What will be the output?

Python