MyPython POO 2021V7
MyPython POO 2021V7
Abdelkader BELAHCENE
[email protected]
2 Basic Python 11
2.1 History Command . . . . . . . . . . . . . . . . . . . . . . . . . 11
2.2 Basic Statements . . . . . . . . . . . . . . . . . . . . . . . . . . 11
2.3 Some Methods on String . . . . . . . . . . . . . . . . . . . . . . 16
2.4 Lists . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17
2.5 Other Lists . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20
2.6 Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23
2.7 Exception Handling . . . . . . . . . . . . . . . . . . . . . . . . . 32
2.8 Regular Exception . . . . . . . . . . . . . . . . . . . . . . . . . . 36
2.9 Turtle . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 40
4 POO in Python 50
4.1 Everything is Object . . . . . . . . . . . . . . . . . . . . . . . . 50
3
Contents Page 4
5 GUI: Tkinter 66
5.1 Presentation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 66
5.2 Widgets . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 67
1.1 Introduction
You can get Documents and Programs example from the FTP local (if you are
in ENST) at the Server at address : 172.16.200.10. Use gftp program, and
login as anonymous (ftp protocole).
Maybe you ll see programs or documents, but you can’t download it, un-
til the permission is given. I do this to give the opportunity to write you
program.
Then, later, if you do not succeed in writing or want to verify your pro-
gram, you’ll find an example of solution, at your disposal, I’ll add read-
ing permission to the file at the appropriate time.
5
1.1. Introduction Page 6
ls /media/mx194/Ventoy/snapshot/ -lh
total 5.2G
-rwxrwxrwx 1 mx194 mx194 1.7G Oct 10 21:40 MX-19.4_386.iso
-rwxrwxrwx 1 mx194 mx194 3.6G Oct 4 11:14 mx21BCustom0410.iso
-rwxrwxrwx 1 mx194 mx194 54 Oct 4 11:14 mx21BCustom0410.iso.md5
1. Use a text editor, we preferably use geany (but gedit or another one
may be fine).
Example 1. Suppose we want to convert a list of images (say 120 images !!!)
gif to png image. With a graphics tool converters, we have to open each
image, export in the new format.
Repeating this task 120 times is really painful, arduous and takes time. Now,
look at this command (just one loop command!!!), try it yourself
Solution 2. The variable “i” takes successively the name of the file, listed by
the command «ls *.gif», convert it to the new format. That’s it !!
• Open the Terminal on half of the screen and on the other half the Editor
(eg geany).
pwd gives the current directory. pwd stands for ---> Path Working Directory
ls -lrt /etc List files and directory of the «/etc» with option details (-l),
sort by time (-t) in reverse order (-r). To sort by size use (-S).
cat file.txt Displays the contents of the file «file.txt». With «zcat» you
can display a compressed text file. (On-the-fly decompression when
displaying).
rm f*.txt removes all files starting with «f» having extension txt. Be careful
with this command!!!
ls > f1.txt The list of the current directoy is stored in the file f.txt. If the
file f.txt exist , it’s content is erased. With the symbol “>>”, the list is
appended (added at the end) to the content..
Open geany editor, write in some sentences, save the content as file.txt in
your Docs folder. Comeback to the terminal, go to Docs. List the content
with details (use ls -l ), you should find your file.txt.
The whole system (hard disks, CDROM, flash Disk or remote media on other
machines !!) is attached to the root denoted by the symbol “/”.
The main folders, attached to the root are :
/bin,/usr/bin contains basic (binary) commands, for example ls, cat, mkdir,
..
/home contains user directories. Each user has a folder in this directory.
• The «ls» command with different options (-l, -lt, -lS, -lrt)
Remark 6. (Classroom work) Keep all your work and programs in your Progs
Folder. Puts the documents you use in the Docs folder. At the end of the
session you should take your programs in flask disk.
In Debian-like linux distribution like (Debian, MX, mint, Ubuntu,...), just use
apt-get install asciinema to install it, or download it and install it with
dpkg -i. You must be administrator.
Asciinema is a small, but very useful program to record and play a terminal
session.
To record a terminal session, just type in terminal : asciinema rec nameOfFile,
and all what you do in the terminal is store the file.
For this reason, if you open a file to read from or to write in, use a text-text
editor like nano. Nano opens the file in a terminal, and all what you do in
nano editor is stored. But if you open graphical editor like geany, gedit, ... ,
which opens a window outside the terminal, ALL you do out the terminal is
not saved.
To finish recording, type CTRL-D.
So, to see the recorded session just type in terminal : asciinema play nameOfFile.
In practice, maybe, you want to see rapidly the session to have just an idea,
before following the different steps of the session, that ’s easy, give the speed
option.
For example : asciinema play -s 4 nameOfFile plays the session 4 times
faster. And you can also play more than one session, each one on a terminal.
Remark 7. Since there is no sound attached to the file, you can write expla-
nations in the terminal, however you must start with a «#» symbol, to tell to
shell, it is a comment and not a command .
Example 8. Run the following session firstly with speed 10, to get a idea
about the subject, then with normal speed. Of course you can run it again
and again. Get from the server the file Demo.cast and check it. The python
program used is given here. Execute the command, for example with speed
10, asciinema play -s 10 mkdir.cast Then without -s option to follow
and execute the commands.
If you want to pause the playing, just hit the space key. Hit it again to
continue.
This demo tests the following commands :
cd
mkdir Docs Progs
cd Progs/
nano p1.py
this file contains : v=input("Please your Name : ")
print(" Hello : ", v)
ls -l
python3 p1.py
cd
cd Docs
pwd
cd ..
pwd
Exercise 9. Use the previous demo. Create in your home Folder : Docs and
Progs directories. Go to Progs folder, create the file p1.py using nano, test the
program. Create another file p2.py with same commands but, now, use the
geany editor. Don’t forget to save p2.py in the Progs Folder.
Basic Python
In this Chapter, we give a summary, through examples, of the essential ele-
ments of the Basic Python. For more details consult for example our docu-
ment “myPython_Base_2021”.
2.2.1 Operators
Binary logic & (binary AND), | (Binary OR), ~ (NOT: 1’s complement), ^
(binary exclusive OR), >> (right shift), << (left shift)
11
2.2. Basic Statements Page 12
a, b = 23, 115
c, e = a | b, a & b
c, e contain (119, -24)
e, f = ~ a, ~ b
e, f contain (-24, -116)
Example 11. Run the following program, try to understand the result. Get
the files operators.py and operators.cast from the our local server
A = ’salam’
B = A + ’alaykum’
01011 + 01110
C = A * 2 + B
A, B gives ----> (’salam’, ’salam alaykoum’)
C gives ----> (’salam salam salam alaykoum’)
The words «A» and «myText» are variables, on the other hand «salam alayk-
oum» is a string and so it is surrounded by character «’», (we can also use the
double quote «"»)
To read from the keyboard we use the «input» instruction, we can display a
help message, before reading like:
The variable «msg» receives the string entered by the keyboard, the message
between "(,)" is displayed as an indication (this message can be ignored).
When we want to receives a value (integer or real number), we ca use «eval»
function (or float or int) to convert the string to value.
By the way the function eval () can evaluate a mathematical expression.
Check the code:
import math as m
eval( "m.sin(3.1)**2+ m.cos(1.67)")
gives the value ----> -0.09731208511033676
x, y =eval( input("2 real Numbers : "))
2 real Numbers : 12.345, -1.55
print(" Sum : ", x+y) gives ----> Sum : 10.795
Formatted outputs
We can precise how to print the data, specially the numbers, by using the
keyword format, here are some examples
Example 12. Using the format keyword after the string to format
Between « {}» we put the number of the variable and the format, that {0:6d}
means the variable 0, here is «a»,is displayed in 6 decimal positions, {2:25s},
displays the third variable as a string in 25 positions. Note that numbers are
right justified while string are left justified. We print again «a», we give it the
its index. If nothing is given between «{}», it is displayed in the order of the
variables, in the default format.
The presence of ":" is mandatory for any block (while, for, if, or functions).
The instructions in a block, must be preceded by a tabulation or a character.
Avoid mixing tabulation and character (make an indentation).
The newline (without indentation) ends the block. We can obviously have
nested blocks.
for i in 12,15,55,38:
if i> 20: ## Tab or space
print (i, "> 20") ## two tabs or spaces
output ---> 55 > 20
output ---> 38> 20
Example 13. The following instructions show: 12 small and even, 17 is odd,
22 is large and even.
i=10
for i in range(10,28,3): while i < 28:
Exercise 15. Write a program that displays: (Use the «for» then «while»
command)
x = "salam alaykum"
x.strip (’um’)
x.find (’am’)
the count method, count the number of occurrence for the argument. We
can also use the string without a name like ’salam’.upper() gives —->
’SALAM’
x.count (’a’)
The split method breaks the string into list of elements, using a separator, by
default the separator is «space».
x.split(’;’)
x.replace(’a’,’AA’)
Exercise 16. Check all theses operations and examples from yourself. Firstly
run the recorded file string.cast ( get it from our local server)
2.4 Lists
A list is a set of objects grouped together under the same name. The objects
are not necessary of the same type, like
By the way my_list is an object of the class list, which has methods, for
example to add an element at the end of my_list, we use the append
method:
myL.append(’salam’)
myL [1][ 3]
You can also build a list with the list constructor, «list» like this: aList = list
(); aList is now an empty list object.
The access to items is done by using index (use square brackets []), we start
at 0, we can start at the end by using negative index.
Most of these methods directly modify the list (except copy). That is the list
is modified after using the method, and doesn’t return anything.
pop retrieves from the list the element whose index is given as an argument
(by default the last one, which is equivalent to pop (-1) and removes it
from the list.
del removes an element from the list by giving its index. this is a function
and not a method, i.e we write: del ll [2] and not ll.del (2).
split splits a string into a list according to the criteria given in argument.
join is the reverse operation of split. It creates a string from the list. The
leading characters are used as the joining element.
append, insert
LL[1] .append ("Hello")
del LL [1]
copy method
LL2 = LL.copy ()
LL2 gives ---> [[’fs’, ’666’, ’aa’], [’33’, ’rt’]]
LL2.reverse ()
LL2 gives ---> [[’33’, ’rt’], [’fs’, ’666’, ’aa’]]
LL2[1] gives ---> [’33’, ’rt’]
sort method
LL2[1] .sort ()
LL2 gives ---> [[’33’, ’rt’], [’666’, ’aa’, ’fs’]]
LL2.sort(reverse=True)
LL2 gives ---> [[’666’, ’aa’, ’fs’], [’33’, ’rt’]]
Customized sort, let consider a dictionary, and sort according the key ( see
lambda function in section : 2.6.6 on page 29 )
d= [{’name’: ’ali’, ’age’: 25}, {’name’: ’omar’, ’age’: 23}, {’name’: ’said’, ’age’: 35}]
d.sort(key=lambda x : x[’age’], reverse=True)
d gives --->
[{’name’: ’said’, ’age’: 35}, {’name’: ’ali’, ’age’: 25}, {’name’: ’omar’, ’age’: 23}]
split, join
ch = "dar-el-chabab-boumerdes"
type(ch)
lst2 = ch.split (’-’)
type(lst2)
lst2 ---> gives [’dar’,’el’,’chabab’,’boumerdes’]
ch2 = "***".join (lst2)
ch2 ---> gives ’dar *** el *** chabab *** boumerdes’
Exercise 17. Check all theses operations and examples from yourself. Firstly
run the recorded file list.cast ( get it from our local server)
2.5.1 Tuples
Python defines another type of list called "tuples", constructed using "(,)" and
not "[,]". But tuples are not editable, modifiable.
Tuples are preferable to lists, when passing them to a function, for example,
which should not modify them. tuples are "readOnly" lists.
Example 18. Example 1. We define t1 and t2 as tuples. List operations are
the same
The zip function creates tuples objects from each element of the arguments:
Example 19. Here we create tuples, every element of the tuple takes one
from each entry, like
2.5.2 Dictionary
Yet another type of list are the dictionaries, which are modifiable but not
ordered, and access is by key, and not by index.
A dictionary is created using braces "{,}". To find an element we put the key
between brackets. Note here that the addition of element is done by a simple
assignment, in particular the key, for the lists one uses rather the function
append.
Example 20. Creating and using a dictionary:
Note that the order in which the values are saved is not necessarily the one
given at the creation.
The keys method returns the keys of the dictionary and values returns the
values
d.keys()
d.values()
The list if values or keys may be obtained with the «list()» function
dd=list(d.values()) ; dd
cc=list(d.keys()) ; cc
v1 = [2, 4, 6, 8 ]
v2 = [3 * x for x in v1]
Exercise 23. We want to create a dictionary for students, we mean the name
followed by the grade, like : {’Berkane’: 14, ’zaichi’: 12.5}, we have the list of
the name et the corresponding grades. Test with the following lists:
students=[’Berkane’,’Zaichi’,’Chabi’, ’Morsli’,’Bensid’]
grades=[14, 12.5, 15, 11.5, 9]
2.6 Functions
2.6.1 Definition
The creation of user functions is done by the keyword: "def". A function can
admit several parameters as input and may return a value.
Exercise 24. Add to the example 2.4 the recursive form for the factorial func-
tion
LAB1
Get the programs from my Server
return 2 * ll
gives ----> 50
If several arguments are used, the arguments provided are taken in the order
given, the missing ones are the last in the list
Example 25. In the first case no argument is given, "a, b and c", keep the
default values. In the second case, the 2 arguments provided are assigned to
“a” and “b”, c receives the default value. Note that the type of the variable
is defined by its content
aa = 3 * a; bb = 4 * b; cc = 2 * c;
return aa, bb, cc
a1, b1, c1 = ff ()
print ("a1: {} b1: {} c1: {}".format (a1, b1, c1))
In the last case, the argument "a" receives 25, "c" receives "GOOD", and "b"
keeps the default value. i.e : 34.5.
a1,b1,c1=ff(c=’OK’, 13)
The statement a1, b1, c1 = ff (c = ’GOOD’, 25) gives an error, the provided
values (here: 25) must be the first, in the list of arguments. All the formal
argument must be given first!!
List type arguments are passed by reference, that is, any modification of the
argument in the function is done on the calling object.
Example 26. In this case, the content of "mylist" is modified in the function
LL.append (547);
myList = [1,2,3]
change (myList]
print (myList)
displays ----> [1, 2, 3, 547],
Be carefully with the assignment, the object is not duplicated, it just creates
a reference, i.e a new name for the same memory space. We can check it by
using the id (Object Identifier).
Example 27. Consider the following program. Notice the id of object v1 and
v2 are the same, which means, v1 and v2 reference to the same memory
location.
13 v3=Copy(v1)
14 print("Vector 3 it’s Id :\t", id(v3))
15 print(v3)
16 ## ---------------------------------------
17 v1[0]=999
18 print("v1 is Modified \nv1[0] :\t\t",v1[0])
19 print("v2[0] :\t\t", v2[0])
20 print("v3[0] :\t\t", v3[0])
21 ’’’
22 Prog$ python3 reference.py
23 Vector 1 it’s Id : 140431382574400
24 [1, 2, 3.4, 11]
25 Vector 2 it’s Id : 140431382574400
26 [1, 2, 3.4, 11]
27 Vector 3 it’s Id : 140431381165952
28 [1, 2, 3.4, 11]
29 v1 is Modified
30 v1[0] : 999
31 v2[0] : 999
32 v3[0] : 1
33 ’’’
In the following code, while the «w» variable is just an other name (same id)
for the «v» variable, «vv» is a new space ( with different id) where values of
v are copied.
v=[1,2,3,4]
w=v
vv=[x for x in v]
id(v) ---> 139824555062464
id(w) ---> 139824555062464
id(vv) ---> 139824554079104)
A function accepts any list of arguments, the number arguments not being
known while writing the function.
The formal arguments (always provided) must be given at the beginning, the
others are preceded by a "*".
A function can also receive a dictionary as an argument. We use "**" in front
of the variable. The most complete declaration is : f1 (a, b, *c, **d).
Here «a» and «b» are formal, «c» is a list and «d » is a dictionary.
Example 28. Here is a complete example, how to use list and dictionary as
argument of function
Python provides through the sys module, the procedure for retrieving these
arguments. The argument as read as a string, so in case we need numbers
we have to convert them.
Example 30. As shown in the example (see the recorded demo :
functions.cast), we use eval to convert the string of digits to numbers.
Check the value of the system variable «$?», after running the program, if
there is no error, you ’ll, 0 otherwise, if you haven’t supplied required
argument, you ’ll get «43», see the exit function in the program. To print this
value, in terminal type : echo $?
The function returns Expression to the variable myVar and admits as argu-
ment the elements arg1, ...., argn
Example 31. Here is a sum function, with 2 arguments. The variable sum
receives the sum of the 2 arguments. Please, note here the «+» operator is
overloaded. Note also, sum is a function and not a simple variable.
def sum(a,b):
return a+ b
Example 32. We create inside the function «myFunc», another function called
«Local». The variable "a" declared non-local in the Local function is there-
fore the same as the variable "a" of parent function myFunc. The variable «b»
is declared Global, so in the same as the the «b» declared in the program (
outside the function myFunc).
However, in otherFunc, the variables are just used and not declared so they
keep last value known in the program.
2.6.8 Files
Text Files
After that (opening procedure), if there is no problem, one can read from or
write in the file.
Example 33. The file must firstly be opened, the following code copy a text
file to another file.
copyFile(’e.txt’, ’f.txt’)
• A division by 0
• an undefined variable
a = 12, b = 0
a / b -----> ZeroDivisionError: division by zero
b = ’8’; a / b -----> TypeError: unsupported operand type (s)
a / c -----> NameError: name ’c’ is not defined
open (’file.txt’) -----> FileNotFoundError: No such file or directory
open (’ff.txt’) -----> PermissionError: Permission denied:
Raising the exception means, predict what to do in the one of these errors
occurs, or what to do in general case. And thus let the program continue,
when an exception is detected.
To achieve this goal and purpose objective, one must plan to throw an excep-
tion for each type, and what to do in each case.
We can also provide a raiser for any exception, as will be seen in detail.
We then try the instruction block:
try :
except:
Example 35. In this program , we have handled the errors of type "TypeEr-
ror", the program has to continue, but not the exception "ZeroDivisionError",
the program did not display the last message.
Exercise 36. Replace, in the program 2.9 on the previous page the second
“TypeError” with “ZeroDivisionError” and verify that the program ends cor-
rectly.
We can put several exception in one «except» clause. If we omit the Error
from the clause, then any exception is accepted, unfortunately, the help is not
clear enough fro the use. For example , if you just say the entered «is not cor-
rect», it is not enough, is there a TypeError, ZeroDivisionError, NameError,
....?
Example 37. This is more complete example, for getting a real number
corresponding to rational number. The program still ask for values (
integers ), until the values entered are correct.
4 except ValueError :
5 print (" Not an integer value entered ")
6 else :
7 break
8
9 print(" Program continues ")
10 while 1:
11 try :
12 d=int(input(’denominator ?:\t ’))
13 r= n / d
14 except (ValueError,ZeroDivisionError) :
15 print (" Value entered (not int or 0) is not valid ")
16 else :
17 print(f’Result : {r:12.4}’ )
18 break
19 print(" End of Program")
Remark 38. The number of exceptions can be large, but it is not necessary to
know them all, when throwing an exception the interpreter gives its name.
Example 39. Consider the program in listing 2.11, the keyword "raise" indi-
cates the raising of exception, ie in our example "age <15" is considered as
exception, which will be raised and following line "except" the capture.
The "else" is executed when there is no exception, the "finally" is always
executed. The keyword "assert" is used to say that the condition "age> 20
and age <70" must be verified, otherwise the exception "AssertionError"
must be caught.
13 except AssertionError:
14 print (" Too Old or too young ")
15 finally:
16 print(" End of Program ")
\ Escape character that will have several uses: gives a special meaning to a
character, or in inverse neutralize the special meaning of meta-character.
^ If placed at the very beginning of a class, allows to negate the class, that is,
to find any character that does not belong that object.
. Any character
\S inverse of \s
\t horizontal tabulation
\f vertical space
\n newline
* 0, 1 or more occurrences, the last left character
ma*n matches mn, man, maan, ... but not main
{n,m} This means at least n, and at most m repetitions of the pattern left to
it.
a{2,4} matches daaat, aabc but not badac
[. . . ] A character class: all the characters listed in the class, with the possibil-
ity of ranges whose limits are separated by "-". The «^» inside brackets,
invert the meaning of the expression.
2.8.1 re module
The module re implement the using of Regular Expression. We’ll this thru
examples.
import re
pattern = ’^a...s$’
test_string = ’abrys’
result = re.match(pattern, test_string)
if result: print("Search successful.")
else: print("Search unsuccessful.")
After importing re, the pattern is an re, we put r in front of the pattern to
avoid any ambiguity, and trait pattern as a Regular Expression.
The String is the character string in which we are looking for the pattern.
The flag
The flag allows us to precise type of correspondence we are looking for (also
valid for search and replacement). Here are the meaning of some flags
re.I Ignore the case, both uppercase and lowercase are allowed
Match
Search
The "search" function works like "match" except that match searches for the
match at the start of the string while search searches for it anywhere in the
string.
findall
Replace
Replace one character string with another, use the re.sub command.
split
19
20 # if the flag is N, split only at Nth occurrence
21 result = re.split(pattern, string, 2) #, flag)
22 print(f’ Splitting Result {result}’)
23
24 ## Substitute
25 phone = " 0775 - 353 - 321 # my friend mobile "
26 num = re.sub(r’#.*’, "AA", phone)
27 print ("Phone number without comment : \n", num)
28 num = re.sub(r’\D’, "", phone)
29 print ("Phone number : ", num)
30
31 ## multiline string
32 string = ’abc 12\
33 de 23 \n f45 6’
34
35 # matches all whitespace characters
36 pattern = ’\s+’ ## space, \t, \n
37 new_string = re.sub(pattern, "", string)
38 print("remove spaces :",new_string)
2.9 Turtle
The graphical part of python is not part of this course, but you should know
that there is a very rich and very easy to use library: matplotlib.
You can also use the tkinter graphics library, integrated into the Python stan-
dard, to create menus, windows and buttons. Here let’s just give a little
schematic plotting program. See chapter 5 on page 66
This is a small module allows you to draw simple figures, with the essential
commands:
backward(size) Backward
up() Lift the pencil (to be able to move forward without drawing)
• The values are not encapsulated, that means: we can read or modify
these values everywhere. Values may not be properly initialized.
• Programming logic and data are scattered, and can be found anywhere.
43
3.2. Response to Theses Problems Page 44
Robustness Ability to react and respond well when deviating from normal
conditions of use.
Portability is the ease with which one can operate the same software in dif-
ferent implementations.
Class Car
A car manufacturer, creates new model car (that is : type of engine, body-
work, power, options, etc.) with the tools and system for starting, braking,
protection, air conditioning, etc.)
After validation of the model, he sets up and configures the machines that
make these cars.
In the object-oriented sense, the model is the class with the attributes (power,
type of engine, fuel, ...) and the methods (accelerating, braking, .... ). So we
have cars of this type manufactured, in our field we call it : the objects of this
class.
When the customer buys a car of a given model, he buys an object of a given
class.
In summary
Student Class
A person (Student) can have Name, Parents, Address, Weight, Height, and
so on, and can also do actions on himself, like Eating, Running, Jumping,
Sleeping, ....
Example 43. Ali Benameur is a 24-year-old student, lives in «martyrs road ,
Algiers» , weighs 73 kg, and is 1m78 tall. He enjoys running and swimming,
but also studying very hard.
• The generalities are contained in the class and the particularities in the
objects.
Abstraction ignore the details to keep only a general notion. we do not act
directly on the data of an object.
Encapsulation: binds together the data and functions that manipulate the
data.
Inheritance: allows you to define a new class from an existing class to which
new data and methods are added. (Specialization and reuse.)
3.3.3 Abstraction
In order to protect the data against mishandling and misuse, some part of
the data of object is declared private and cannot be directly accessible, and is
hidden from the outside to the object.
So to use theses data we need access methods.
We call this concept : abstraction. This means we need an interface to our
class, which contains all required methods.
Example 44. Take the case of driving a car. To increase speed you need an
accelerator pedal, which adjusts the flow of fuel to the carburetor. The driver
does not have to know the quantity, nor to know how the gasoline arrives
and burns etc .... Imagine that the driver manually regulates the quantity
which goes into the carburetor !!!! We can imagine the rest ... !!
Example 45. When you type in the " ls " command in the terminal, you get
the list of files, you don’t need to know neither on which sectors, track and
cylinder of the disk your files are stored, nor the number of pieces constitut-
ing your files !! ! all this is transparent to you (hidden). This means there is
an «Abstraction» or Access interface to manipulate your files. Imagine that
you have to give physical location of the files.
3.3.4 Encapsulation
Put in the object, all what we need : Data and Methods, which them form
a whole. Let’s look at a simple example in which we compare the use of
procedural (through functions) and object oriented programming.
Example 46. Suppose we have a rectangle with a width, a height and a
color. We want a function to display its data. Using the procedural concept,
we write (in python for example) :
print( w, h, s)
We must send 3 parameters, which makes the call heavy, the time of use of a
function depends a lot on the number of parameters. Whereas with OOP,
we just use the method directly on the object ( if myRect is the object):
myRect.display()
The width, height and color values are the properties of the myRect object.
3.3.5 Inheritance
Example 47. Consider a class «Rectangle» containing the data : width and
height, and Display method which prints the data. Now we need a colored
Rectangle, we declare it as a child of Rectangle, and so we inherit width and
height. We just add the color to the colored Rectangle class, and can also use
Display the width and height.
3.3.6 Polymorphism
POO in Python
<class ’int’>
type (b)
<class ’float’>
type (c)
<class ’str’>
type(L)
<class ’list’>
These objects have methods predefined in the language, we can only use
these.
We have seen before, some methods for the String class and List class. Here
are some examples.
The method string method count give the number of occurrence of the
string given in argument. The list method append adds an element to the
list, that is :
50
4.1. Everything is Object Page 51
gives ----> 2
L=[ [ 1,2,3] ]
L.append([11,22,33])
In the same way, we can work around integer or float. We can write for
example:
b.as_integer_ratio ()
c.upper ()
class ClassName:
class myClass:
x = 10
p1 = myClass
print (p1.x)
displays --------> 10
We create the class "myClass" with a single attribute "x". We create an object
“p1” of type “myClass”, we display the attribute x of the object p1.
Remark 49. . The data is directly accessible. Here we are not yet talking about
a private, protected or public attribute. We will see later how Python deals
with these notions.
• An object constructor
class Student:
Explanations
• The __init__ function, (you have to write it like this) is called each time
an object is created (it is the equivalent of a constructor in other lan-
guages such as C ++, for example.
• The first argument “self” (by convention, but we can give it any other
name) is used to differentiate argument variables from attributes. Here
age is the argument self.age is the attribute. The "self" argument indi-
cates the current object which is being processed.
class member
The attribute Student.Number relates to the class attribute. But can also be
used by an object. Indeed the attribute Number, does not concern any object
but the whole class.
Thus Number contains the number of object of the class, which must be up-
dated each time an object is created or deleted.
Using the class «Student» :
We add to our class a «display» method which prints the information about
a student object, the complete program is
As all the attributes and methods of the Student class are public, you can
modify any attribute or delete it.
Conversely to «__init__» method, which creates a new object, the method
«__del__» delete an object. Thus «__init__» is called when a new object is
declared, « __del__» is called hen an object is removed. We can then write:
18 def __del__(self):
19 Student.Number -= 1
20
21 s1=Student(’ali’,25)
22 s2=Student(’omar ’,22)
23 s3=Student(’moussa’,35)
24 s1.display()
25 s2.display()
26 s3.display()
27
28 print("Size of Student Class : ", Student.Number)
29 ###del s2
30 ##print("Size of Student Class : ", Student.Number)
31 ##s2.display() ## gives error and stops program
32 ’’’
33 try :
34 s2.display()
35 except:
36 print(" the object doesn’t exist ")
37 ’’’
38
39 msg=’’’\n\n Using the exception clause, the program ends normally,
40 otherwise, the program is stopped with error. Check in the terminal
41 the value of environment variable $?.
42 Run the program with and without the try bloc, and in each case
43 run the system command ; echo "value returned : $? "
44 if the program ends normally, it returns 0
45 otherwise other value, and this message is not printed \n
46 ’’’
47 print(msg)
LAB2
width, height the number of characters used to draw the rectangle. The rect-
angle consists of height rows, each row by width columns. By default
theses values are 1.
pattern this pattern is used to draw the rectangle. By default the value is ’*’.
display prints the attributes of the rectangle. That’s width, height, perimeter
, area and pattern
draw draw the rectangle as height lines of the pattern. An offset is given to
right shift the drawing.
r1 = Rectangle(25, 3, ’+’)
r2 = Rectangle(8, 4)
r1.width
r1.display() ; r1.draw()
r2.display() ; r2.draw(15)
r3=Rectangle()
r3.display() ; r3.draw()
• Put the data inside of the program (number of rows, columns, offset
and pattern)
Python does not have a special word for private or protected like C ++ or
Java, but instead uses a notation on the variable.
If all the attributes are public, an essential principle of object orientation ("Ab-
straction") is not respected.
Apart from these special cases, the data is accessible and public.
Let’s go back to the “Student” class and replace the Number variable with
__Number. In this case the instructions:
Give errors. We must then add to the class a public method which displays
this number and a method which retrieves the age.
Example 52. The class becomes as follows. Note the absence of self for the
class method.
def age(self):
return self.__age;
4.3 Inheritance
Consider In the following example, the listing file (presented like this for ease
of reading) must be split into several files as shown: person.py student.py
employeee.py testPerson.py.
Consider the inheritance scheme as follows:
Example 53. The program testPerson.py, uses theses classes. Since each
class is defined alone in a file, we import all theses files . So the first
statements are the import. Here is the code of the programs.
In the same way, when we call the Display method for the Employee (or Stu-
dent), we call the Display method of the Person. So the printing information
( name, address, ...) concerning the Employee or Student are not duplicated
in theses classes, it is written just once in the Person Class.
The statement if __name__==’__main__’: used in pers.py (we can use it in
other files), is to prevent the execution of the following statements if the file
is used as a module.
in other words, if we run the program like : python3 pers.py, the __name__
variable will contain __main__, then the commands Iam=Person(.....), son=Person(.....)
are executed, otherwise, they will be skipped.
Exercise 54. Modify the programs, using other data, run each file alone
4.4 Packaging
When importing the package, Python searches thru the stp3andard directo-
ries and subdirectories declared on the path : sys.path.
The __init__.py file is required to make Python treat directories containing
the files as packages. This prevents directories with a common name, such as
string, unintentionally hiding valid modules that occur later on the module
search path.
In the simplest case, __init__.py can just be an empty file, but it can also exe-
cute initialization code for the package or set the __all__ variable, described
later.
Now what happens when the user writes from sound.effects import *? Ide-
ally, one would hope that this somehow goes out to the filesystem, finds
which submodules are present in the package, and imports them all. This
could take a long time and importing sub-modules might have unwanted
side-effects that should only happen when the sub-module is explicitly im-
ported.
The only solution is for the package author to provide an explicit index of
the package. The import statement uses the following convention: if a pack-
age’s __init__.py code defines a list named __all__, it is taken to be the list
of module names that should be imported when from package import * is
encountered. It is up to the package author to keep this list up-to-date when
a new version of the package is released. Package authors may also decide
not to support it, if they don’t see a use for importing * from their package.
Example 55. Let’s see all this in an example. Consider the files of classes :
Person, Employee, and Student
LAB3
AnalyseNum A.Belahcene December 13, 2021
4.4. Packaging Page 62
Create a class, named «polygon» which is a base class for Square. A square
is a regular polygon with 4 edges.
The polygon has number of edges, and length of edge. The Polygon displays
the position of its nodes.
Consider a polygon with N nodes, where length of side is L. We calculate the
internal angle of the polygon with int_Angle= 180 (N-2)/ N.
We want to draw the polygon centered at position (0,0), so we shift left the
starting point by on x-axis with L/2 and down shift by L/(2 tan(π/N ))
Create a file for polygon class, a file for Square class and a file main to check
the classes.
The entered values must be checked for validity, with following conditions :
3 ≤ N ≤ 10 and 50 ≤ L ≤ 250. Consider the try/except block to check the
entered values.
The polygon has a drawing method using the turtle package, see the section
2.9 on page 40. The polygon has method to calculate the perimeter.
Square has its proper methods to calculate the area and perimeter. The rect-
angle has another method to draw the rectangle in terminal a matrix of a
given character.
We consider a character on terminal as 16x16 pixels image, so divide the
length L by 16 to get the number of rows to print on terminal.
Here is a demonstration;
python3 Lab3.py
python3 Lab3.py
4.5.1 isinstance
The isinstance () function allows you to test the type of an instance, that is
to say the type of an object, that is to say, allows you to know whether an
object belongs to a certain class or not.
4.5.2 issubclass
4.5.3 __doc__
class Student:
s1.__ doc__
----> prints exactly the comment inserted in the class, that is: The Student
class has 2 attributes .......
4.5.4 __dict__
This method gives information about an object or a class. In our case (
Student class ),
4.5.6 __help__
__init __ (self, n, d)
__mul __ (self, a)
poster (self)
GUI: Tkinter
5.1 Presentation
An example of using OOP is the Tkinter GUI. Let’s analyze this simple little
example. We will come back with more details on the different objects, here
we give an idea on the tkinter module.
Example 57. Creating a basic window with text
import tkinter as tk
myFen = tk.Tk ()
message = tk.Label (myFen, text = "Salam Alaykoum!")
message.pack ()
myFen.mainloop ()
66
5.2. Widgets Page 67
Explanation
• import the tkinter package, we can also import ttk (set for tk themes) which
is newer and allows more themes.
• Creation of the Base Window object myWin = tk.Tk ()
• Add a Label object (containing text) to the base window myWin
• Place the Label object by default in the window, the options allow you to
choose the position, top, bottom, ... with the pack placement method.
• Two other placement methods exist: place and grid. In the following we
will use grid which seems simpler and more precise to use.
• Keep the Displayed Window with the mainloop loop.
5.2 Widgets
Any "widget" must be attached to the base "window" which will contain ev-
erything else.
The graphical interface is the application par excellence that uses the OOP.
We are going to write our interface using the object oriented principle.
For all our programs we import tkinter like this: import tkinter as tk
5.2.1 window
A window is a rectangle to be drawn on screen with an N-E position and a
dimension.
myWin = tk.Tk ()
topmost indicates that the window will be above other windows on the
screen. you can also specify with lift and lower to move it forward
and back in the list of windows.
Remark 59. Until then, the program guides the user, now we are going to do
programming by event, that is to say the program remains listening to the
events of the user, and responds to the keyboard key or. of the mouse.
We can also use a recent addition to tkinter which supports ttk themes
In our case, the mainloop function listens to the keyboard and the mouse,
and responds to these events.
For example, clicking on a button triggers the execution of a code.
5.2.2 Label
A label is a text added in its container, ie the window which contains it. We
specify the container, the parent class, (which contains this Label), here fen.
This is valid for all widgets: button, menu, etc ...
The format for creating a widget is to specify the options as a dictionary in
addition to the parent class:
etiq = tk.Label (fen, background = ’yellow’, font = ("Helvetica", 16))
The options are given as a dictionary, for example background = ’yellow’,
font = ("Helvetica", 16).
The most common options
anchor When the text is smaller than the box, it is placed in the center, on
the left (W: West) or on the right (E: East) with tk.W, tk.E or tk.CENTER
textvariable the text can be modified with the variable of type StringVar
wraplength sets the length (in pixels) of the text before carriage returns.
changes the background color of the label object to blue. Which means the
presentation can be changed dynamically. For example retrieve the name of
the color from an entry.
Example 60. We complete our window by adding a Label, we obtain the
listing 5.2. Here we did not specify the size of the window, it will be
determined by the size of the objects it contains.
The pack method allows you to specify the location of the message object in
the fen object. Here we add internal and external spaces in x and y (ipadx,
...,) to the text.
We obtain the Figure 5.2.1 on the following page
Question 61. What is the size of the program window 5.2.1 on the next page
5.2.3 Button
The appearance properties (background, font, padx, ....) of Button are
practically the same as for Label, the essential thing to consider is the
command to execute when clicking on the button object. As the following
instruction indicates:
btn = tk.Button (myWin, text = ’In Blue’, background = ’blue’, command = colorB)
// The btn object is placed in the “myWin” window type object with a blue
background. When you click on the btn object, the colorB function is
executed. See the example of listing 5.3.
5.2.4 Grid
The grid is simply a grid or matrix, in which the positions are indicated by
the row number and column number, for example:
The help object is placed in row 2, column 3 frame on the right (sticky = tk.E).
The resSum object is placed in row 3 and column 2 by taking the entire width
of the box with sticky (tk.E + tk.W, East-West) , i.e from left to right.
The hlpBtn object is placed from column 1, on 2 columns (columnspan = 2)
We can also do a placement on several rows with rowspan
5.2.5 Frame
A frame is a frame or container that can group other widgets. It is thus
possible to create groups of objects in the same window and each group in a
frame. For a complete example see Listing 5.4.
21
22 self.exp1 = tk.Entry(self.frameInput)
23 self.etiq1 = tk.Label(self.frameInput, text="Exp1 :")
24 self.exp2 = tk.Entry(self.frameInput)
25 self.etiq2 = tk.Label(self.frameInput, text="Expression 2 :")
26 self.res = tk.Label(self.frameInput, text=’Here the Result’)
27
28 self.etiq1.grid(row =1,column=1)
29 self.exp1.grid (row =1,column=2)
30 self.etiq2.grid(row =2,column=1)
31 self.exp2.grid (row =2,column=2)
32 self.res.grid(row =3, column =1)
33
34 self.som = tk.Button(self.frameBtn,text=’Sum’,
35 command=self.Sum)
36 self.prod = tk.Button(self.frameBtn,text=’Product’,
37 command=self.Product)
38 self.quit = tk.Button(self.frameBtn, text=’Exit’,
39 command=myWin.quit)
40 self.som.grid(row =1, column =1)
41 self.prod.grid(row =2, column =1)
42 self.quit.grid(row =3, column =1)
43
44 def Sum(self):
45 try:
46 rr=eval(self.exp1.get()) + eval(self.exp2.get())
47 except:
48 self.res.config(text=theText, foreground=’red’)
49 else:
50 ss="Result: "+rr.__format__(’.3f’)
51 self.res.config(text = ss , foreground=’blue’)
52 def Product(self):
53 try:
54 rr=eval(self.exp1.get()) * eval(self.exp2.get())
55 except:
56 self.res.config(text=theText, foreground=’red’)
57 else:
58 ss="resultat: "+ rr.__format__(’.3f’)
59 self.res.config(text = ss , foreground=’blue’)
60
61 if __name__==’__main__’:
62 myWin=tk.Tk()
63 myWin.title(’Frame and Entry Example’)
64 app=myFrame(myWin)
65 myWin.mainloop()
myWin= tk.Tk ()
frame = tk.Frame (myWin, background = ’blue’)
frame.grid (row = 1, column = 1)
The Frame "frame1" is inside myWin Window, and contains the entry "ent1"
placed as indicated, with grid widget.
5.2.6 Entry
The Entry widget allows the user to enter data, somewhat the opposite of
Label which allows text to be displayed. In this example from listing 5.4 on
page 72 we discuss the grid placement method.
5.2.7 Menu
Listing 5.5: barMenu Example
1 importtkinter as tk
2 classmyMenu():
3 def__init__(self, master):
4 self.master=master
5 menubar=tk.Menu(master)
6 master.config(menu=menubar)
7 file_menu=tk.Menu(menubar)
8 edit_menu=tk.Menu(menubar)
9
10 #menubar.grid(row=1,column=1)
11 #addamenuitemto themenu
12 file_menu.add_command(label=’Ouvrir’,command=self.ouvrir )
13 file_menu.add_command(label=’Exit’,command=master.destroy )
14 file_menu.add_command(label=’Quitter’,command=self.quitter )
15
16 edit_menu.add_command(label=’Copier’,command=self.copier)
17
18 #addthe Filemenuto themenubar
19 menubar.add_cascade(label="Fichier",menu=file_menu)
20 menubar.add_cascade(label="Edition",menu=edit_menu)
21 defcopier(self):
22 print(" Copier le Texte ")
23 defouvrir(self):
24 print(" Ouverturedefichier ")
25 def quitter(self):
26 print(" Destructionde la Fenetre ")
27 self.master.destroy()
28
29 if __name__==’__main__’:
30 fen=tk.Tk()
31 fen.title(’ExempledeFrameet Entry’)
32 fen.geometry("400x300")
33 app=myMenu(fen)
34 fen.mainloop()
5.2.8 Canvas
57 w.pack()
58
59 p = 50
60 t = 15
61
62 nsteps = 10
63 step_x = int(canvas_width / nsteps)
64 step_y = int(canvas_height / nsteps)
65
66 for i in range(1, nsteps):
67 polygon_star(w,i*step_x,canvas_height - i*step_y,p,t,outline=’red’,fill=’gold’, widt
68
69 mainloop()
70 """
LAB4
The goal of this Lab is to manipulate tkinter widgets : buttons and Canvas.
As is described in the figure 5.2.2. see also the program canva.py
1. Canvas window : Receives the graphs of filled Circles and filled Poly-
gon. Create a class, named «polygon» which is a base Menu window
contains:
Scrollbar Link a scroll bar to a scrolling widget, for example a Text widget.
radioButton uses radio buttons to allow users to select one of many mutu-
ally exclusive choices.
Slider Learn how to create a slider using the Tkinter Scale widget.
Sizegrip guides on how to use the Sizegrip widget to allow users to resize
the entire application window.
LabelFrame shows you how to group related widgets into a group using the
LabelFrame widget.
progressbar shows you how to use the progress bar widget to give user
feedback on the progress of a long-running task.
Treeview guides you through the steps of creating treeview widgets that
display tabular and hierarchical data.