Workshop OOP - Workshop OOP - Discover object-oriented programming

Overview

Workshop OOP

Découvrez la programmation orientée objet

C'est quoi un objet ?

Un objet est une instance de classe. C'est une structure de données qui contient des variables ou des fonctions (ou d'autres objets).

Un équivalent grossier en C:

typedef struct
{
    int data1;
    char data2;
} object;

// Plus tard dans le code

object *obj = malloc(sizeof(object));
// obj->data1
// obj->data2

Une structure en C permet de stocker des données. Le principe est le même avec un object, avec des comportements supplémentaire.

Du coup c'est quoi une classe ?

Un objet est une instance de classe.

Ok, c'est bien beau mais c'est quoi ce truc ? Une classe est un type de données, un modèle qu'on utilisera pour créer un objet.

Si on reprend l'exemple du dessus, la "classe" serait la définition de la structure.

En Python ça se passe comment ?

Créer un objet

La déclaration d'une classe se fait comme suit:

class Klass:
    def __init__(self):
        self.data1 = 5
        self.data2 = 'c'

Dans l'utilisation:

def main():
    obj = Klass()
    print(obj.data1)
    print(obj.data2)

Un peu d'explication s'impose. Comme dit plus haut, un objet contient des variables (qu'on va nommer attributs) et des fonctions (des methodes).

La fonction __init__ (ou méthode, vu qu'elle est définie dans une classe) sert à construire l'objet. C'est dans cette fonction qu'on va initialiser les attributs de notre objet.

Rien n'empêche par la suite de modifier les valeurs:

def main():
    obj = Klass()
    print(obj.data1)
    print(obj.data2)
    obj.data1 = 156
    obj.data2 = 'Other'
    print(obj.data1)
    print(obj.data2)

C'est quoi self ?

self est une variable spécifique, qui doit être présente dans chanque méthode que vous déclarez. Elle est en faite une référence sur l'obet qui appelle la méthode.

class Klass:
    def __init__(self):
        self.data1 = 5
        self.data2 = 'c'

    def print(self):
        print(self.data1, self.data2)

def main():
    obj = Klass()
    obj.print()  # Pas besoin de redonner 'obj' en paramètre, ça se fera tout seul :)
    Klass.print(obj)  # Là on récupère la méthode depuis la classe, il lui faut donc l'objet à utiliser

On peut donner plusieurs arguments à une méthode ?

Bien sûr !

class Klass:
    def __init__(self, data1, data2):
        self.data1 = data1
        self.data2 = data2

    def print(self):
        print(self.data1, self.data2)

def main():
    obj = Klass(5, 'c')  # N'oubliez pas que ça va implicitement appeler __init__
    obj.print()

Pourquoi ne pas directement appeler __init__ ?

Bah essayons:

class Klass:
    def __init__(self, data1, data2):
        self.data1 = data1
        self.data2 = data2

    def print(self):
        print(self.data1, self.data2)

def main():
    obj = Klass.__init__(<something>, 5, 'c')  # Vous mettez quoi à la place de <something> ?
    obj.print()

S'il a été possible d'initialiser notre objet, c'est qu'il a bien été créé à un moment précis. Le processus de création d'un objet va le créer, puis appeler le constructeur afin que vous puissiez l'initialiser.

Pourquoi faire des objets ?

Modéliser la vie réelle

Un objet sert avant tout à modéliser des choses de la vie réelle. Un attribut sert à garder des informations sur ce qu'on modélise, tandis qu'une méthode définit une action possible avec notre objet.

Prenons l'exemple d'une personne. On sait qu'une personne a:

  • un prénom
  • un nom
  • un âge

Du coup toutes ses informations seront les attributs de notre objet.

Maintenant, il est possible qu'une personne sache parler (en théorie) pour se présenter. Ce sera fait avec une méthode.

class Person:
    def __init__(self, first_name, last_name, age):
        self.first_name = first_name
        self.last_name = last_name
        self.age = age

    def present(self):
        print(f"My name is {self.first_name} {self.last_name}. I am {self.age}.")

def main():
    jack = Person("Jack", "Anderson", 38)
    john = Person("John", "Doe", 56)
    jack.present()
    john.present()

Tout ce qu'on a dit a été retranscrit dans une classe Person, et on peut se servir des objets pour créer (littéralement) une personne.

Owner
Francis Clairicia-Rose-Claire-Joséphine
Francis Clairicia-Rose-Claire-Joséphine
SpaCy3Urdu: run command to setup assets(dataset from UD)

Project setup run command to setup assets(dataset from UD) spacy project assets It uses project.yml file and download the data from UD GitHub reposito

Muhammad Irfan 1 Dec 14, 2021
An async API wrapper for Dress To Impress written in Python.

dti.py An async API wrapper for Dress To Impress written in Python. Some notes: For the time being, there are no front-facing docs for this beyond doc

Steve C 1 Dec 14, 2022
Script for resizing MTD partitions on a QNAP device in order to be available to upgrade from buster to bullseye

QNAP partitions resize for kirkwood devices. As explained by Marin Michlmayr, Debian bullseye support on kirkwood QNAP devices was dropped due to [mai

Arnaud Mouiche 26 Jan 05, 2023
C++ Environment InitiatorVisual Studio Code C / C++ Environment Initiator

Visual Studio Code C / C++ Environment Initiator Latest Version : v 1.0.1(2021/11/08) .exe link here About : Visual Studio Code에서 C/C++환경을 MinGW GCC/G

Junho Yoon 2 Dec 19, 2021
This repository can help you made a PocketMine-MP Server with Termux apps!

Hello This GitHub repository can made you a Server PocketMine-MP On development! How to Install Open Termux Type "pkg install git && python" If python

1 Mar 04, 2022
Developing a python based app prototype with KivyMD framework for a competition :))

Developing a python based app prototype with KivyMD framework for a competition :))

Jay Desale 1 Jan 10, 2022
An optional component handler for hikari, inspired by discord.py's views.

hikari-miru An optional component handler for hikari, inspired by discord.py's views.

43 Dec 26, 2022
Todos os exercícios do Curso de Python, do canal Curso em Vídeo, resolvidos em Python, Javascript, Java, C++, C# e mais...

Exercícios - CeV Oferecido por Linguagens utilizadas atualmente O que vai encontrar aqui? 👀 Esse repositório é dedicado a armazenar todos os enunciad

Coding in Community 43 Nov 10, 2022
Web interface for browsing, search and filtering recent arxiv submissions

Web interface for browsing, search and filtering recent arxiv submissions

Andrej 4.8k Jan 08, 2023
Python scripts to interact with Upper Deck ePack online trading card platform

This script should connect to the Upper Deck ePack API using your browser cookies and download a list of your current collection and save it as a CSV.

Adrian Kent 1 Nov 22, 2021
Program Input Data Mahasiswa Oop

PROGRAM INPUT NILAI MAHASISWA MENGGUNAKAN OOP PENGERTIAN OOP object-oriented-programing/OOP adalah paradigma pemrograman berdasarkan konsep "objek", y

Maulana Reza Badrudin 1 Jan 05, 2022
Bible-App : Simple Tool To Show Bible Books

Bible App Simple Tool To Show Bible Books Socials: Language:

ميخائيل 5 Jan 18, 2022
🌈Python cheatsheet for all standard libraries(Continuously Updated)

Python Standard Libraries Cheatsheet Depend on Python v3.9.8 All code snippets have been tested to ensure they work properly. Fork me on GitHub. 中文 En

nick 12 Dec 27, 2022
Up to date simple useragent faker with real world database

fake-useragent info: Up to date simple useragent faker with real world database Features grabs up to date useragent from useragentstring.com randomize

Victor K. 2.9k Jan 04, 2023
Kivy program for identification & rotation sensing of objects on multi-touch tables.

ObjectViz ObjectViz is a multitouch object detection solution, enabling you to create physical markers out of any reliable multitouch solution. It's e

TangibleDisplay 8 Apr 04, 2022
The RAP community of practice includes all analysts and data scientists who are interested in adopting the working practices included in reproducible analytical pipelines (RAP) at NHS Digital.

The RAP community of practice includes all analysts and data scientists who are interested in adopting the working practices included in reproducible analytical pipelines (RAP) at NHS Digital.

NHS Digital 50 Dec 22, 2022
An alternative app for core Armoury Crate functions.

NoROG DISCLAIMER: Use at your own risk. This is alpha-quality software. It has not been extensively tested, though I personally run it daily on my lap

12 Nov 29, 2022
PyPI package for scaffolding out code for decision tree models that can learn to find relationships between the attributes of an object.

Decision Tree Writer This package allows you to train a binary classification decision tree on a list of labeled dictionaries or class instances, and

2 Apr 23, 2022
Geodesic Dome Math

dome Geodesic Dome Math Python dome tool dome.py calculates an icosahedron or 2v geodesic dome and creates 3d printable hubs as OpenSCAD sources. usag

Brian Olson 2 Feb 09, 2022