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
ChieriBot,词云API版,用于统计群友说过的怪话

wordCloud_API 词云API版,用于统计群友说过的怪话,基于wordCloud 消息储存在mysql数据库中.数据表结构见table.sql 为啥要做成API:这玩意太吃性能了,如果和Bot放在同一个服务器,可能会影响到bot的正常运行 你服务器性能够用的话就当我在放屁 依赖包 pip i

chinosk 7 Mar 20, 2022
Quick script for automatically extracting syscall numbers for an OS

Syscalls-Extractor Quick script for automatically extracting syscall numbers for an OS $ python3 .\syscalls-extractor.py --help usage: syscalls-extrac

m0rv4i 54 Feb 10, 2022
Retrying is an Apache 2.0 licensed general-purpose retrying library, written in Python, to simplify the task of adding retry behavior to just about anything.

Retrying Retrying is an Apache 2.0 licensed general-purpose retrying library, written in Python, to simplify the task of adding retry behavior to just

Ray Holder 1.9k Dec 29, 2022
A Python version of Canvacord

A copy of canvacord made in python! Table of contents Installation Examples Creating Images Links Downloads Installation Run any of these commands in

10 Mar 28, 2022
Mannaggia is a python application to praise or more likely to curse the saints

Mannaggia-py 👼 Remember Mannaggia? This is a Python remake of it, with new features. mannaggia is a python application to praise or more likely to cu

Christian Visintin 9 Aug 12, 2022
Paprika is a python library that reduces boilerplate. Heavily inspired by Project Lombok.

Image courtesy of Anna Quaglia (Photographer) Paprika Paprika is a python library that reduces boilerplate. It is heavily inspired by Project Lombok.

Rayan Hatout 55 Dec 26, 2022
A Puzzle A Day Keep the Work Away

A Puzzle A Day Keep the Work Away No moyu again!

P4SSER8Y 5 Feb 12, 2022
Resources for the 2021 offering of COMP 598

comp598-2021 Resources for the 2021 offering of COMP 598 General submission instructions Important Please read these instructions located in the corre

Derek Ruths 23 May 18, 2022
Python project setup, updater, and launcher

Launcher Python project setup, updater, and launcher Purpose: Increase project productivity and provide features easily. Once installed as a git submo

DAAV, LLC 1 Jan 07, 2022
Collection of Python scripts to perform Eikonal Tomography

Collection of Python scripts to perform Eikonal Tomography

Emanuel Kästle 10 Nov 04, 2022
Lightweight and Modern kernel for VK Bots

This is the kernel for creating VK Bots written in Python 3.9

Yrvijo 4 Nov 21, 2021
Nateve transpiler developed with python.

Adam Adam is a Nateve Programming Language transpiler developed using Python. Nateve Nateve is a new general domain programming language open source i

Nateve 7 Jan 15, 2022
Bootcamp de Introducción a la Programación. Módulo 6: Matemáticas Discretas

Módulo 6: Matemáticas Discretas Última actualización: 12 de marzo Irónicamente, las matemáticas discretas son las matemáticas que lo cuentan todo. Si

Cynthia Castillo 34 Sep 29, 2022
Collection of functions for working with interlaced content in VapourSynth.

vsfieldkit Collection of functions for working with interlaced content in VapourSynth. It does not have any hard dependencies outside of VapourSynth.

Justin Turner Arthur 11 May 27, 2022
Antchain-MPC is a library of MPC (Multi-Parties Computation)

Antchain-MPC Antchain-MPC is a library of MPC (Multi-Parties Computation). It include Morse-STF: A tool for machine learning using MPC. Others: Commin

Alipay 37 Nov 22, 2022
Source for the Fedora Silverblue and Kinoite variants.

Source for the Fedora Silverblue and Kinoite variants.

Fedora Kinoite 7 Aug 20, 2022
Python’s bokeh, holoviews, matplotlib, plotly, seaborn package-based visualizations about COVID statistics eventually hosted as a web app on Heroku

COVID-Watch-NYC-Python-Visualization-App Python’s bokeh, holoviews, matplotlib, plotly, seaborn package-based visualizations about COVID statistics ev

Aarif Munwar Jahan 1 Jan 04, 2022
Utility to play with ADCS, allows to request tickets and collect information about related objects

certi Utility to play with ADCS, allows to request tickets and collect information about related objects. Basically, it's the impacket copy of Certify

Eloy 185 Dec 29, 2022
Launcher program to select which version of the Q-Sys software to launch.

QSC-QSYS Launcher Launcher program to select which version of the Q-Sys software to launch. Instructions To use the application simply save the "Q-Sys

Zach Lisko 2 Sep 28, 2022
Automatically deletes Capital One Eno virtual cards for when you've made a couple too many.

eno-delete Automatically deletes Capital One Eno virtual cards for when you've made a couple too many. Warning: Program will delete ALL virtual cards

h3x 3 Sep 29, 2022