Python Tutorial – Classes and Objects (9)

Python Tutorial – Classes and Objects
Python Tutorial – Classes and Objects

Python is a development language that has become very popular in application development. We will continue to move forward by looking at classes and objects in python and how to manipulate them.

Previous tutorial: Tutorial Python – Loops (8)

Classes and Objects

Python is one of the object-oriented programming languages, a fundamental concept in modern development languages. An object is a container for elements and also provides functions to create dynamic behaviors.

This enables the creation of behaviors, unlike lists and dictionaries that need to be manipulated externally.

Defining a Class

A class is defined simply like this:

class Fruit:

Similar to a dictionary, you can insert elements into it. However, their declaration is different:

class Fruit:
nom = ''
    poids = 0

Here, we define the names of our elements and assign them default values.

So far, if you’ve followed the previous tutorials, you might not see much difference from a dictionary in concept. Let’s explore what differentiates the two from now on.

In classes, you can create behaviors by adding functions inside them. Some functions, known as “magic” functions, are automatically triggered based on certain actions.

The most commonly used is the __init__ function, which is executed every time an object is created from a class.

Before discussing this function, it’s essential to understand the term “object.” When we define a class, we can create one or more objects from it.

  • Banana is a Fruit
  • Apple is a Fruit

Banana and Apple have similar characteristics, as you can guess. However, the two remain different things. With our Fruit class, we can create two different objects (Banana and Apple) with similar characteristics.

We’ll see later how to create these objects from the Fruit class.

Let’s get back to the __init__ function, which is triggered every time a new object is created from the class. This can be very useful, for example, to fill in our “nom” and “poids” elements, which are similar characteristics of each Fruit but will have different values.

class Fruit:
    nom = ''
    poids = 0
    def __init__ (self, nom, poids):
        self.nom = nom
        self.poids = poids

We need to break down the declaration of our __init__ function because we discover new elements.

  • Like a regular function, declare our function with the keyword def.
  • The first parameter self of the __init__ function is mandatory and allows returning an instance of the object itself (in essence, self allows manipulating the object created from the class itself).
  • nom and poids are parameters internal to the function. Pay attention! These parameters, even though they have the same name as the parameters of the class, represent variables internal to the function, not parameters of the class.
  • self.nom and self.poids allow accessing the parameters of the class. self.nom = nom thus assigns the value of the function to the value of the parameter of the class.
  • To reach the parameters of the class itself, you will always need to use self! If you forget self, you will only manipulate a parameter of the function. A function parameter is destroyed when the program finishes executing the function, whereas a class parameter remains available until the object is destroyed. The scope is entirely different.

Creating an Object from my Class

I mentioned object creation earlier, so I will now give you a way to create an object from this class.

Learn from the example below:

class Fruit:
    nom = ''
    poids = 0
    def __init__ (self, nom, poids):
        self.nom = nom
        self.poids = poids
        banane = Fruit("banane", 50)

By doing Fruit("banane", 50), I will create an object of type Fruit to which I send two parameters, which, thanks to the automatically triggered __init__ function, will insert these values into the parameters of the class. Remember that self is mandatory, and you only specify it when creating an object from the second parameter onwards.

Certainly, you can access the parameters of the class in this way, using the . (dot) operator:

class Fruit:
    nom = ''
    poids = 0
    def __init__ (self, nom, poids):
        self.nom = nom
        self.poids = poids
       
banane = Fruit("banane", 50)
print(banane.nom)

This will print what we passed to “nom,” namely “banane” in the following example.

From the same class, we can create two different objects, as I explained earlier:

class Fruit:
    nom = ''
    poids = 0
    def __init__ (self, nom, poids):
        self.nom = nom
        self.poids = poids
banane = Fruit("banane", 50)
pomme = Fruit("pomme", 100)

More Complex Classes

Although there are default functions in classes, it is possible to create our custom functions. Here’s an example with custom functions that would allow inserting parameters on demand.

class Fruit:
    nom = ''
    poids = 0
    def setName(nom):
        self.nom = nom
    def setWeight(poids):
        self.poids = poids
banane = Fruit()
banane.setName("banane")
banane.setWeight(50)

Here, I no longer use the __init__ function but two functions to insert the parameters. In the following example, it may seem tedious, but it can be very useful to understand the different possibilities that Python offers.

We will use the . (dot) operator to call one of the functions of the class, as you can see in the previous example. If you have understood the concept of functions seen in a previous chapter, you should not find any difficulty in this latest example.

Conclusion – Classes and Objects

We have seen a first draft of creating classes and objects in Python, which is essential to know to create quality programs. We will go further in the next chapter of our learning about Python, which still holds many secrets.

Next Chapter: Tutorial Python – Advanced Object Concepts (10)

(Visited 36 times, 1 visits today)
About Judicaël Paquet 368 Articles
Judicaël Paquet (agile coach and senior devops) My Engagements in France and Switzerland: - Crafting Agile Transformation Strategies - Tailored Agile Training Programs - Raising Awareness and Coaching for Managers - Assessing Agile Maturity and Situational Analysis - Agile Coaching for Teams, Organizations, Product Owners, Scrum Masters, and Agile Coaches Areas of Expertise: Scrum, Kanban, Management 3.0, Scalability, Lean Startup, Agile Methodology.

Be the first to comment

Leave a Reply

Your email address will not be published.


*