The Python class and Python objects are a crucial part of the language. You can’t properly learn Python without understanding Python classes and objects. In this chapter, you will learn:
- How in Python everything is an object
- To define your own Python class
- Create objects based on a class
- What inheritance is
When you’re just creating small scripts, chances are you don’t need to create your own Python classes. But once you start creating larger applications, objects and classes allow you to organize your code naturally. A good understanding of objects and classes will help you understand the language itself much better.
Python objects: a look under the hood
Before we dive into all the details, let’s start by taking a look under the hood. I do this because I believe it will give you a much better understanding of these concepts. Don’t let the length of this page discourage you. After reading it thoroughly, and trying the examples yourself, you should have a good understanding of classes and objects in Python.
OK; let’s dive in! You probably know the built-in len() function. It simply returns the length of the object you give it. But what is the length of, say, the number five? Let’s ask Python:
>>> len(5)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: object of type 'int' has no len()</module></stdin>Code language: Python (python)
I love errors because they illustrate how Python works internally. In this case, Python is telling us that 5 is an object, and it has no len(). In Python, everything is an object. Strings, booleans, numbers, and even Python functions are objects. We can inspect an object in the REPL using the built-in function dir(). When we try dir on the number five, it reveals a big list of functions that are part of any object of type number:
>>> dir(5)
['__abs__', '__add__',
'__and__', '__bool__',
'__ceil__', '__class__',
...