ELI5 Tutorial: Objects in Python

In today’s ELI5 I will go over objects in python. This is going to be a long one, but by the end of it you will understand the basics of objects in python.

You’ve Seen Objects Before. Kind Of?

If you’ve done any sort of intro level python work then you are no doubt familiar with data types like strings or lists. You will probably have noticed that these data types have some sort of built in function that either changes or displays parts of the data. For example, take the code below:

--- myWord = "hello"
--- myWord.replace('l', 'L')
"heLLo"

This example behaves quite similar to objects in python. There is a “string” object that holds a sequence of letters and it has methods like “replace” that are functions which interact with the data the string is holding. In other words, objects are simply a datatype that you define to suit your needs.

Defining a Car

So, lets learn more about how this works by making our own object: a Car object. Our Car object is going to hold two pieces of data, the model of the car and the mileage of the car.

class Car:
    mileage = 0
    def __init__(self, inputModel):
        self.model = inputModel

So, lets go over what I did line by line.
First, I used class Car: to start my definition of the object.
On the next line I gave it an attribute called “mileage” which I set to a default value of 0.
On the next line I defined a special method called __init__ which is short for “initialise”. This is a special method that is used when the class is created, there are a lot of special methods in objects that are usually donated by having a pair of underscore characters like __ before and after the name. I will show some more of those later.
In that init method I have two arguments: self and inputModel. In objects, the very first argument of a method is usually written as self and represents the object itself. In nearly every situation you should always have a self argument in an object.
Finally, I end it with self.model = inputModel. This is adding another attribute to the object called “model” which is equal to the argument “inputModel”.

What this code is going to do is make Car objects which will have an attribute “mileage” equal to 0 and an attribute “model” depending on what the user enters at the start. The user will be able to access these attributes using variableName.attributeName. For example:

--- myHonda = Car("Honda")
--- myHonda.mileage
0
--- myHonda.model
"Honda"

They can also change these directly:

--- myHonda = Car("Honda")
--- myHonda.mileage
0
--- myHonda.mileage = 10
--- myHonda.mileage
10

Car Goes Vrooom!

Now, at this point you may be asking “why not use a dictionary?” This is basically just a set of keys and values accessed in a slightly different way, right? The main power of objects comes from being able to define methods, which is a function that is run on the object. For example, I am going to change my definition to create a method for making a car move.

class Car:
    mileage = 0
    def __init__(self, inputModel):
        self.model = inputModel

    def vrooom(self, distance):
        self.mileage += distance

Now I can define a car and also feed it a function that simulates its motion, that car I can track how far my various car objects have moved.

--- myHonda = Car("Honda")
--- myMazda = Car("Mazda")
--- myHonda.mileage
0
--- myMazda.mileage
0
--- myHonda.vrooom(10)
--- myMazda.vrooom(5)
--- myHonda.mileage
10
--- myMazda.mileage
5

Printing Cars

Remember above when I said that init was a special method and there were more available? You can also define what happens in certain situations using other special methods. For example, what happens if you check if two cars are equal or if a car is greater than another car! I’m going to go with a simple example, what happens when you print a car. I am going to update the definition like so:

class Car:
    mileage = 0
    def __init__(self, inputModel):
        self.model = inputModel

    def vrooom(self, distance):
        self.mileage += distance

    def __str__(self):
        output = f"Hello, I am a {self.model} and I have traveled {self.mileage} miles"
        return output

The __str_ method is a special method for objects that defines the output when the object is converted into a string. My code uses fstrings (found in python 3.6+) to output string where the object states the model and distance travelled for the car. Here is it in action:

--- myHonda = Car("Honda")
--- print(myHonda)
"Hello, I am a Honda and I have traveled 0 miles"

To learn more about default objects here is an exercise you can try: update the Car object to add a method to check if two Car objects are equal, which will be when their models and the mileages are the same.

Adding More Attributes

You aren’t limited to adding attributes in the init method. You can add them direct to the object too. For example, below I am going to add a new attribute stating who the owner is.

--- myHonda = Car("Honda")
--- myHonda.owner = "Me"
--- myHonda.owner
"Me"

You can also directly change the initialised attributes without using methods:

--- myHonda = Car("Honda")
--- myHonda.model = "Honda2"
--- myHonda.mileage = "zero"
--- print(myHonda)
"Hello, I am a Honda2 and I have travelled zero miles"

Conclusion

There we have it, you now know how to create and use objects. For simple scripting you will likely not feel like you need to use these feature, but when you go into something more advanced the power of objects may help greatly.

One of the main advantages would be for easily making modular code, where you can take objects out and put them direct into another piece of code, subclassing if necessary to add or change its functions. The next ELI5 tutorial will deal with subclassing.

This entry was posted in ELI5, Python, tutorial and tagged , . Bookmark the permalink.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.