• 6 heures
  • Facile

Ce cours est visible gratuitement en ligne.

course.header.alt.is_video

course.header.alt.is_certifying

J'ai tout compris !

Mis à jour le 21/01/2021

Define objects and their attributes with classes

Connectez-vous ou inscrivez-vous gratuitement pour bénéficier de toutes les fonctionnalités de ce cours !

You've probably heard the term object in a programming context before but what does it mean?Let's start by looking at some real-world objects like pens, books, smartphones, computers, and so on.

All sorts of objects!
All sorts of objects!

Objects come in different forms and shapes, but you can classify different versions of the same item into a category or group. It's why you can go to a furniture store and recognize different items as chairs even if they look very different from one another.

You recognize different objects as being part of the same group or type as well as noticing commonalities between different ones, collecting information, and creating a mental representation for a category.

For example, there are different kinds of books out there, but they all have a title, an author, a cover, page, etc. Individual books all have similar attributes that allow you to classify them in your mind as part of the category: book.

Books of different sizes, colors, and lengths
Books of different sizes, colors, and lengths

This mental list of attributes just described for a book acts as a kind of blueprint for that object. In programming, it's called a class. When creating a class, you can come up with any custom name you desire, which is why classes are called a named type. As you'll see, they also allow you to group lots of details together, which is also why they can be referred to as complex types. On the other hand, the simple types you are already familiar with, like int or double have names that are  predefined by the programming language and cannot be modified. 

How do you come up with class names?

Similar to naming variables, class names must be descriptive and spelled out (remember, avoid abbreviations!). A key difference is that, instead of using standard camel case, the first letter should also be capital, e.g. MarvelousCreature and not marvelousCreature.

Designing classes

To see how to design a class, let's continue with the book example.  Below, we've identified a sample of information that could describe any book:

  • Title

  • Author

  • Number of pages

  • Publisher

Those are attributes of any book in real life. In Python, in the context of classes, they are also called attributes. They are simply a fancy name for something you're already familiar with: variables!

Now that you understand the theory let's put it in writing!

To declare a class in Python, use the keyword class followed by a custom name. After that, you end it with a colon (:).

class Book:

Now let's add attributes as defined earlier:

class Book:
def __init__(self, title, author, numberOfPages, publisher):
self.title = title
self.author = author
self.numberOfPages = numberOfPages
self.publisher = publisher

We owe you some explanations. All classes have a function called __init__(), which is executed when the class is being initiated. That means that every time you create a Book, the __init__() function is called. The first parameter of the method should always be self, which represents the class you are working on. For example, self.title will be the title assigned to the Book class just created.

Another important thing to learn is to indent. Python is a block-structured language meaning that every group of statements in a program or script (called block) has to be indented. For example, after the first line, every indented code referring to the class Book: __init__ is only available in Book. The same goes for all the self. lines. They are only available in the __init__ function and only in Book.

Using classes

Now that the new type - Book  📖 - is sorted out, what can you do with it? After all, classes are more abstract. Class fields are like an online bookstore template: searches always result in the same information such as title, author, number of pages, etc.

When you're searching for something to read, you don't just type "book," right? That's not useful! You need a specific instance of a book, like Alice in Wonderland. You're looking for an actual object you can page through and read. It's the same in computer programming.

To work with a class, you need to create a concrete object of that class. In other words, you need a specific object, like a particular book (Alice in Wonderland). In Python, it is called an instance of a class. As its name implies, the process is called instantiating or initializing an object.  For that, you create a variable of the class.  

In Python, each field of the created object must have a value which can be provided in a few ways.  You saw one earlier with the publisher example: hard-setting a value in the class definition. 

Another way is providing a value in the statement that creates the class. Let's look at how to do that. Here is the code for creating a book with values provided at the moment the object is created:

Instantiation of an object

As you can see, there are a few different elements. First, you do a regular declaration of a variable, with its name myBook.

Now, here comes the cool part. The variable is initialized with the object creation expression   Book("Coding is art","Becky James",425, "OC"). This expression is composed of the name of the class again (Book), and some parentheses() with values inside. As you can see, the value for each of the original fields:  title,  authornumberOfPages, and publisher has been specified in the parenthesis. Each one is separated with a comma. You now have an instance of the class Book! 📔

Working with attributes

Phew!  That was a lot of vocabulary and concepts.  Before we move on, let's recap with a quick diagram:

From class to object!
From class to object!

Does that help? Just remember:

  • You use a class as a template for future objects. 

  • In a class, define the name and type of some variables. These are called attributes in Python. 

  • To use the plan you made, you have to create an object by the process of instantiation. This means declaring a variable, then using the object creation expression you saw above. 

  • When you instantiate an object, you create values for each of the attributes you've already defined in your class.  

  • An object is called an instance of a class. 

You've got your book object, but what if you change your mind about the value of your variables? How do you access the associated attributes?

A common way to access attributes in many programming languages is using what's called a dot notation. To do this, you write the name of an instance or object followed by an attribute name of interest, separated by a dot: instanceVariableName.attributeName.

myBook.title = "Coding is Art"
myBook.author = "Becky James"
myBook.numberOfPages += 10

Now you can set change the value of your fields within the object! Imagine that you've added 10 pages because you forgot to add the book's index. You could either type the new number directly or like you see in the third line, add 10 pages to the existing value. This is pretty handy when making small changes. 🙂

Try it yourself

Console de code
Houston... ?
Il semblerait que votre ordinateur ne soit pas connecté à Internet.
Vous n'êtes pas connecté

Connectez-vous pour accéder aux exercices de codes et testez vos nouvelles compétences.

Pensez à vous entraîner avant de terminer ce chapitre.

Summary

In this chapter, you've learned the fundamentals of objects:

  • A class is a blueprint of an object.

  • A variable of a class is called an instance of a class, or an object.

  • A class allows you to create complex types by grouping and defining attributes. 

  • To create an object, you need to declare a variable of a class and instantiate it.

  • The dot notation provides access to attributes.

Exemple de certificat de réussite
Exemple de certificat de réussite