Modularité

by Christian Nguyen, Joseph Razik, last modified on 2019-10-18
modularite

Importation brute et risquée

In [1]:
from modulex import *
importation => execution ?
In [2]:
try:
    print(_x)
except NameError as e:
    print("error : ", e)
_x = 2
print('_x = ', _x)
y = y + 3
print('y = ', y)
print()
try:
    _f()
except NameError as e:
    print("error : ", e)
g()
error :  name '_x' is not defined
_x =  2
y =  4

error :  name '_f' is not defined
Bienvenu
3.141592653589793
In [3]:
# de l'intérêt de ne PAS utiliser "import *"
def g():
    print('surprise !')
In [4]:
g()
surprise !

Importation de module: the right way

In [5]:
import modulex as m
print('m._x = ', m._x, 'm.y = ', m.y)
m.g()
m._f()
m._x =  0 m.y =  1
Bienvenu
3.141592653589793
Defense d'entrer
In [6]:
m.set_x(-5)
m.set_x(42)
print('x = ', m.get_x())
[set_x] erreur : parametre entier negatif
x =  42

Différence module / main, test unitaire avec: if __name__ == '__main__':

In [7]:
print(__name__)
__main__
In [8]:
import math
print(math.__name__)
math
In [9]:
import modulex
print(modulex.__name__)
modulex