Classes and Objects in Python

This is the 1st article in a series on Object-Oriented Programming:


Classes and Objects are the fundamental concepts of Object-Oriented Programming.

In Python, everything is an object!

A variable (object) is just an instance of its type (class).

That\’s why when you check the type of a variable you can see the class keyword right next to its type (class).

This code snippet shows that my_city is an object and it is an instance of the class str.

my_city = "New York"
print(type(my_city))
<class 'str'>

Differentiate Class x Object

The class gives you a standard way to create objects, a class is like a base project.

Say you are an engineer working for Boeing.

Your new mission is to build the new product for the company, a new model called 747-Space, this aircraft flies higher altitudes than other commercial models.

Boeing needs to build dozens of those to sell to airlines all over the world, the aircrafts have to be all the same.

To guarantee that the aircrafts (objects) follow the same standards, you need to have a project (class) that can be replicable.

The class is a project, a blueprint for an object.

This way you make the project once, and reuse it many times.

In our code example before, consider that every string has the same behavior, the same attributes, so it only makes sense for strings to have a class str to define them.

Attributes and Methods

Objects have some behavior, this behavior is given by attributes and methods.

In simple terms, in the context of an object, attributes are variables and methods are functions attached to an object.

For example, a string has many built-in methods that we can use.

They work like functions, you just need to them from the objects using a ..

In this code snippet, I\’m calling the replace() method from the string variable my_city which is an object, and instance of the class str.

The replace() method replaces a part of the string for another and returns a new string with the change, the original string remains the same.

Let\’s replace \’New\’ for \’Old\’ in \’New York\’.

my_city = 'New York'
print(my_city.replace('New', 'Old'))
print(my_city)
Old York
New York

Creating a Class

We have used many objects (instances of classes) like strings, integers, lists, and dictionaries, all of them are instances of predefined classes in Python.

To create our own classes we use the class keyword.

By convention, the name of the class matches the name of the .py file and the module by consequence, it is also a good practice to organize the code.

Create a file vehicle.py with the following class Vehicle.

class Vehicle:
    def __init__(self, year, model, plate_number, current_speed = 0):
        self.year = year
        self.model = model
        self.plate_number = plate_number
        self.current_speed = current_speed

    def move(self):
        self.current_speed += 1

    def accelerate(self, value):
        self.current_speed += value

    def stop(self):
        self.current_speed = 0

    def vehicle_details(self):
        return 'Model: ' + self.model + ', Year: ' + str(self.year) + ', Plate: ' + self.plate_number

Let\’s break down the class to explain it in parts.

The class keyword is used to specify the name of the class Vehicle.

The <strong>init</strong> function is a built-in function that all classes have, it is called when an object is created and is often used to initialize the attributes, assigning values to them, similar to what is done to variables.

The first parameter self in the <strong>init</strong> function is a reference to the object (instance) itself, we call it self by convention and it has to be the first parameter in every instance method, as you can see in the other method definitions def move(self), def accelerate(self, value), def stop(self), and def vehicle_details(self).

Vehicle has 5 attributes: year, model, plate_number, and current_speed.

Inside the <strong>init</strong>, each one of them is initialized with the parameters given when the object is instantiated.

Notice that current_speed is initialized with 0 by default, meaning that if no value is given, current_speed will be equals to 0 when the object is first instantiated.

Finally, we have three methods to manipulate our vehicle regarding its speed: def move(self), def accelerate(self, value), def stop(self).

And one method to give back information about the vehicle: def vehicle_details(self).

The implementation inside the methods work the same way as in functions, you can also have a return to give you back some value at the end of the method as demonstrated by def vehicle_details(self).

Using the Class

Use the class on a terminal, import the Vehicle class from the vehicle module.

Create an instance called my_car, initializing year with 2009, model with \’F8\’, plate_number with \’ABC1234\’, and current_speed with 100.

The self parameter is not taken into consideration when calling methods, the Python interpreter infers its value as being the current object/instance automatically, so we just have to pass the other arguments when instantiating and calling methods.

Now use the methods to move() the car which increases its current_speed by 1, accelerate() which increases its current_speed by the value given in the argument, and stop() wich sets the current_speed to 0.

Remember to print the value of current_speed at every interaction to see the changes.

To finish the test, call vehicle_details() to print the information about our instantiated vehicle.

>>> from vehicle import Vehicle
>>>
>>> my_car = Vehicle(2009, 'F8', 'ABC1234', 100)
>>> print(my_car.current_speed)
100
>>> my_car.move()
>>> print(my_car.current_speed)
101
>>> my_car.accelerate(10)
>>> print(my_car.current_speed)
111
>>> my_car.stop()
>>> print(my_car.current_speed)
0
>>> print(my_car.vehicle_details())
Model: F8, Year: 2009, Plate: ABC1234

If we don\’t set the initial value for current_speed, it will be zero by default as stated before and demonstrated in the next example.

>>> from vehicle import Vehicle
>>>
>>> my_car = Vehicle(2009, 'F8', 'ABC1234')
>>> print(my_car.current_speed)
0
>>> my_car.move()
>>> print(my_car.current_speed)
1
>>> my_car.accelerate(10)
>>> print(my_car.current_speed)
11
>>> my_car.stop()
>>> print(my_car.current_speed)
0
>>> print(my_car.vehicle_details())
Model: F8, Year: 2009, Plate: ABC1234