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
DC619/DC858 Mainframe Environment/Lab

DC619 Training LPAR The file DC619 - Mainframe Overflows Hands On.pdf contains the labs and walks through how to perform them. Use docker You can use

Soldier of FORTRAN 9 Jun 27, 2022
VAST - Visualise Abstract Syntax Trees for Python

VAST VAST - Visualise Abstract Syntax Trees for Python. VAST generates ASTs for a given Python script and builds visualisations of them. Install Insta

Jesse Phillips 2 Feb 18, 2022
Sync SiYuanNote & Yuque.

SiyuanYuque Sync SiYuanNote & Yuque. Install Use pip to install. pip install SiyuanYuque Execute like this: python -m SiyuanYuque Remember to create a

Clouder 23 Nov 25, 2022
Annotates sequences with Eggnog-mapper and hhblits against PDB70

Annotating "hypothetical" proteins with the PDB See config/ for configuration information. This workflow takes as input a set of protein sequences. It

1 Apr 05, 2022
An end-to-end Python-based Infrastructure as Code framework for network automation and orchestration.

Nectl An end-to-end Python-based Infrastructure as Code framework for network automation and orchestration. Features Data modelling and validation. Da

Adam Kirchberger 15 Oct 14, 2022
This Program Automates The Procces Of Adding Camos On Guns And Saving Them On Modern Warfare Guns

This Program Automates The Procces Of Adding Camos On Guns And Saving Them On Modern Warfare Guns

Flex Tools 6 May 26, 2022
Code and yara rules to detect and analyze Cobalt Strike

Cobalt Strike Resources This repository contains: analyze.py: a script to analyze a Cobalt Strike beacon (python analyze.py BEACON) extract.py; extrac

Tek 224 Jan 04, 2023
A stupid obfuscation thing

StupidObfuscation A stupid obfuscation thing How it works The obfuscator takes a string, splits into pieces of one, then, using the table from letter.

Echo 2 May 03, 2022
Why write code when you can import it directly from GitHub Copilot?

Copilot Importer Why write code when you can import it directly from GitHub Copilot? What is Copilot Importer? The copilot python module will dynamica

Mythic 41 Jan 04, 2023
edgetest is a tox-inspired python library that will loop through your project's dependencies, and check if your project is compatible with the latest version of each dependency

Bleeding edge dependency testing Full Documentation edgetest is a tox-inspired python library that will loop through your project's dependencies, and

Capital One 16 Dec 07, 2022
Repo to store back end infrastructure for Message in a Bottle

Message in a Bottle Backend API RESTful API for Message in a Bottle frontend application consumption. About The Project • Tools Used • Local Set Up •

4 Dec 05, 2021
Osu statistics right on your desktop, made with pyqt

Osu!Stat Osu statistics right on your desktop, made with Qt5 Credits Would like to thank these creators for their projects and contributions. ppy, osu

Aditya Gupta 21 Jul 13, 2022
Iris-client - Python client for DFIR-IRIS

Python client dfir_iris_client offers a Python interface to communicate with IRI

DFIR-IRIS 11 Dec 22, 2022
Mmr image postbot - Бот для создания изображений с новыми релизами в сообщество ВК MMR Aggregator

Mmr image postbot - Бот для создания изображений с новыми релизами в сообщество ВК MMR Aggregator

Max 3 Jan 07, 2022
Aoc 2021 kedro playground with python

AOC 2021 Overview This is your new Kedro project, which was generated using Kedro 0.17.5. Take a look at the Kedro documentation to get started. Rules

1 Dec 20, 2021
Generate Gaussian 09 input files for the rotamers of an input compound.

Rotapy Purpose Generate Gaussian 09 input files for the rotamers of an input compound. Distance to the axis of rotation remains constant throughout th

1 Jul 16, 2021
Simple Python-based web application to allow UGM students to fill their QR presence list without having another device in hand.

Praesentia Praesentia is a simple Python-based web application to allow UGM students to fill their QR presence list without having another device in h

loncat 20 Sep 29, 2022
디텍션 유틸 모음

Object detection utils 유틸모음 설명 링크 convert convert 관련코드 https://github.com/AI-infinyx/ob_utils/tree/main/convert crawl 구글, 네이버, 빙 등 크롤링 관련 https://gith

codetest 41 Jan 22, 2021
Port of the OpenCascade library to JavaScript / WebAssembly using Emscripten

OpenCascade.js A port of the OpenCascade CAD library to JavaScript and WebAssembly via Emscripten. Explore the docs » Examples · Issues · Discuss Proj

Sebastian Alff 347 Jan 08, 2023
用于导出墨墨背单词的词库,并生成适用于 List 背单词,不背单词,欧陆词典等的自定义词库

maimemo-export 用于导出墨墨背单词的词库,并生成适用于 List 背单词,欧陆词典,不背单词等的自定义词库。 仓库内已经导出墨墨背单词所有自带词库(暂不包括云词库),多达 900 种词库,可以在仓库中选择需要的词库下载(下载单个文件的方法),也可以去 蓝奏云(密码:666) 下载打包好

ourongxing 293 Dec 29, 2022