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
Information about a signed UEFI Shell that can be used when Secure Boot is enabled.

SignedUEFIShell During our research of the BootHole vulnerability last year, we tried to find as many signed bootloaders as we could. We searched all

Mickey 61 Jan 03, 2023
SuperMario - Python programming class ending assignment SuperMario, using pygame

SuperMario - Python programming class ending assignment SuperMario, using pygame

mars 2 Jan 04, 2022
Example applications, dashboards, scripts, notebooks, and other utilities built using Polygon.io

Polygon.io Examples Example applications, dashboards, scripts, notebooks, and other utilities built using Polygon.io. Examples Preview Name Type Langu

Tim Paine 4 Jun 01, 2022
Objetivo: de forma colaborativa pasar de nodos de Dynamo a Python.

ITTI_Ed01_De-nodos-a-python ITTI. EXPERT TRAINING EN AUTOMATIZACIÓN DE PROCESOS BIM: OFFICIAL DE AUTODESK. Edición 1 Enlace al Master Enunciado: Traba

1 Jun 06, 2022
Create an application to visualize single/multiple Xandar Kardian people counting sensors detection result for a indoor area.

Program Design Purpose: We want to create an application to visualize single/multiple Xandar Kardian people counting sensors detection result for a indoor area.

2 Dec 28, 2022
Datamol is a python library to work with molecules.

Datamol is a python library to work with molecules. It's a layer built on top of RDKit and aims to be as light as possible.

datamol 276 Dec 19, 2022
The code behind sqlfmt.com, a web UI for sqlfmt

The code behind sqlfmt.com, a web UI for sqlfmt

Ted Conbeer 2 Dec 14, 2022
Bible-App : Simple Tool To Show Bible Books

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

ميخائيل 5 Jan 18, 2022
mrcal is a generic toolkit to solve calibration and SFM-like problems originating at NASA/JPL

mrcal is a generic toolkit to solve calibration and SFM-like problems originating at NASA/JPL. Functionality related to these problems is exposed as a set of C and Python libraries and some commandli

Dima Kogan 102 Dec 23, 2022
These are After Effects and Python files that were made in the process of creating the video for the contest.

spirograph These are After Effects and Python files that were made in the process of creating the video for the contest. In the python file you can qu

91 Dec 07, 2022
Blender addon, import and update mixamo animation

This is a blender addon for import and update mixamo animations.

ywaby 7 Apr 19, 2022
Forward RSS feeds to your email address, community maintained

Getting Started With rss2email We highly recommend that you watch the rss2email project on GitHub so you can keep up to date with the latest version,

248 Dec 28, 2022
Strawberry Benchmark With Python

Strawberry benchmarks these benchmarks have been made to compare the performance of dataloaders and joined database queries. How to use You can run th

Doctor 4 Feb 23, 2022
Manually Install Python 2.7 pip without any problem !

Python2.7_install_pip Manually Install Python 2.7 pip without any problem ! Download installPip.py to your system and Run the code using this Command

Ali Jafari 1 Dec 09, 2021
A subleq VM/interpreter created by me for no reason

What is Dumbleq? Dumbleq is a dumb Subleq VM/interpreter implementation created by me for absolutely no reason at all. What is Subleq? If you haven't

Phu Minh 2 Nov 13, 2022
LAPS module for CrackMapExec

Crackmapexec-LAPS LAPS module for CrackMapExec Make sure to point to the DC Specify the full domain name Be careful the rid 500 might not be "Administ

28 Oct 05, 2022
Werkzeug has a debug console that requires a pin. It's possible to bypass this with an LFI vulnerability or use it as a local privilege escalation vector.

Werkzeug Debug Console Pin Bypass Werkzeug has a debug console that requires a pin by default. It's possible to bypass this with an LFI vulnerability

Wyatt Dahlenburg 23 Dec 17, 2022
Black-Scholes library implemented as a Cairo smart contract

Cairo Black-Scholes Library Black-Scholes library implemented as a Cairo smart contract. All inputs, outputs, and internal calculations use 27-digit f

Aditya Raghavan 47 Dec 19, 2022
Creates a release pull request updating changelog and tags with standard-version

standard version release branch Github action to open releases following convent

8 Sep 13, 2022
MODSKIN-LOLPRO-updater: The mod is fkn 10y old and has'nt a self-updater

The mod is fkn 10y old and has'nt a self-updater. To use it just run the exec, wait some seconds, and it will run the new modsk

Shiro Amurha 3 Apr 23, 2022