Object Oriented Programming python
new concepts of the object oriented programming :
class
encapsulation
inheritance
polymorphism
the three features of an object are : identity, state and behaviora class is an abstraction which regroup objects who have the same attributes and the same methods.
an object is then an instance of the corresponding class, and it is distinguished from the other instances by its identity and the value of its attributes.
an attribute or a method is privates if their use is forbidden outside of the class.
an attribute or a method is public if their use is allowed outside of the class.
getter : public method, to return an attribute’s value.
setter : public method, to save an attribute’s value
inheritance : relation of specialisation / generalization between two class. it indicates that a class named daughter class specialised another class called mother class. i.e. which own the same methods and attributes of the mother class plus some more which are its own.
ascending : if we use the generalization way, we can find identical attributes and methods in different classes, the inheritance allow you to factor them in order to simplify the creation and the maintenance of the code.
descending : if we use the specialisation way, we create specialised classes for a normal one. the level we want. this is a common way when we want to use again some classes.
multiple inheritance : a normal class can own multiple mother class.
some difficulties may appear when the mother classes own some methods that have the same name and that are not redefine inside the daughter class.
polymorphism(多态性) : a mechanism which allows a subprogram to redefine a method it inherit and for which it will keep the same signature.
depending on the context, the program will choose the right method.
the code may be generated more easily. we can call the same named methods but they will produce a deferent effect depending on the type of the object.
variables in python
python basic type :
int : integers
float : decimals
complex(复数) : complex
bool : booleans
str : strings
dynamic typing :
before using a variable you do not need to explicitly declare its type, the interpreter takes care of that.
this will be done as soon as you assign a value to this variable.
strong typing :
available operations on a variable totally depend on its type.
implicit type conversions to perform certain operations are prohibited.
syntax : myVariable = value
syntax : var1, var2, … = val1, val2,…
one can always check the type of a variable with the command “type”
e.g. : type(myVariable)
using the console mode, one can display the content of a variable just by typing in its name.
to make a display on the console from a script, and / or to perform more sophisticated displays we will need the print command.
syntax : print(expr_1, expr_2, …, sep = ‘ ‘, end = ‘ ’)
note : sep shows what will separate these expressions, by default it is a space. end states that will be displayed at the end after all the expressions, by default it is a return line.( )
eg : age = 30
print(“I am”, age, “years old and in two years I will be “, age+2, “years old”)
e.g. : print(“des”, “traits”, ”bas”, ”pour”, ”séparer”, sep’_’)
print(“et”, “des”, “plus”, “a”, “la”, “suite”, sep=‘_’, end=‘+++’)
print(“et la fin”)
input
syntax : var = input(expression)
note : expression is optional, it is just used to make a display on the input line. what the user will input will be assigned to a var as a string.
eg : a = input
12
print(a, type(a))
b = eval(input(“enter a number : “))
enter a number : >? 12
print(b, type(b))
conditional structure
comparison operators :
< <= > >= == !=
logical operator :
or
and
not
syntax of a simple test :
if conditional :
block of statements to execute if the conditional is true
eg : x = eval(input))
if x < 0 :
x = -x
print(x)
note : blocks of instructions are defined in two ways : (previous line ends with a colon “:” / the entire block is intended according to the instructions preceding and following it.
syntax of a test with an alternatives :
if conditional :
block of statements to execute if the conditional is true
else :
block of statements to execute if the conditional is true
eg : n = eval(input())
if n%2 == 0 :
print(“the number entered is even”)
else :
print(“the number entered is odd”)
syntax of a test with several alternatives :
if conditional :
block of statements to execute if the conditional is true
elif otherConditional :
block of statements to execute if the conditional is true
else :
block of statements to execute if the conditional is true
eg :x = eval(input())
if x < 0 :
print(“the number entered is strictly negative “)
elif x > 0 :
print(“the entered number is strictly positive”)
else :
print(“the number entered is zero”)
iterative structure
range
syntax : range(start, end, step)
note : this function produces a range of values from start(included) to end(not included) with a specified step. the default start and step are 0 and 1 respectively.
eg : range(6)
eg : range(3.6)
eg : range(3,10,2)
eg : range(6,0,-1)
for
syntax : for var in range(start, end, step) :
block of instructions to be repeated while var takes the values of the range defined by range.
eg : n = eval(input())
for i in range(1,11) :
print(i, ’*’, n, ’=‘, n*i)
eg : for i in range(20, -1, -2) :
print(i)
while
syntax : while conditional :
block of instructions to be excited until the conditional is true
eg : x = eval(input())
n = 0 while n+1 <= x :
n+=1
print(“la par tie entière de”, x, “est”, n)
subroutine
procedures
syntax : def myProcedure(para1, para2, …, paraN) :
Instruction bloc of the procedure
eg : def rectangle(x,y) :
print( >>perimeter : “,2*(x+y)”,”.area :”, x*y)
e.g. : def displayGoldenNum() :
print((1+sprt(5))/2)
functions
syntax : def myFunction(para1, para2, …, paraN) :
instruction bloc of the function
return value
eg : def cube(x) :
return x*x*x
eg : deg calculMiniMaxi(x,y) :
id x < y :
return x,y
else :
return y,x
e.g. : print(cube(5))
a,b = 5, -2
min, max = calculMiniMaxi(a,cube(b))
print(“Minimum : “, min, “, Maximum :”, max)
duck typing
eg : def addition(x,y) :
return x + y
print(addition(666,1))
print(addition(“Brown”, ’Sugar’))
default parameters
eg : def rectangle(x=3, y=1) :
print( >> perimeter : “, 2*(x+y), >>area :”, x+y)
rectangle(0) (result is 8,3)
rectangle(2) (result is 6,2)
rectangle(7,5) (result is 24,35)
immutable parameters(不变的)
local and global variables
eg : def sommeEntiers(n) :
somme = 0
for i in range)n+1) :
somme += i
return somme
modules of functions(extension file “.py” that contains subroutines.)
project structure
three methods to import a module :
from NameOfAModule import *
from NameOfAModule import aFunction
import NameOfAModule
sequential data structures
sequence concept
following elements accessible by position.
each element, except the first, has a predecessor and except the last one, a successor.
access an element
mySequence[wantedPosition]
the three main types of sequences :
the lists(whose elements are arbitrary and changeable)
syntax of the declaration of a list :
myEmptyList= [ ]
myListWithOneElement= [ ]
myListe= [element1, element2, …, elementN]
e.g. : myList = [2, -3, [‘xox’, 69],11]
print(myList) result is [2, -3, [‘xox’, 69],11]
print(myList[-1]) result is 11
myList[1] = 666
print(myList[1]) result is 666
print(myList[2] [0] [1]) result is o
N-Tuples(whose elements are arbitrary and unchangeable)
syntax of the declaration of N-tuples :
myEmptyTuple= ()
myTupleWithOneElement= (element)
myTuple= (element1, element2, …, elementN)
e.g. : myTuple=(2.718, 3.14, 1.414)
print(myTuple) result is (2.718, 3.14, 1.414)
print(myTuple[2]) result is 1.414
myTuple[2] = 1.732 result is error
s[i]
s[i:j] : from i(included) to j(excluded).
s[i:j:k] : from j(included) to j(excluded) step by k.
eg : t = (7, -3, 2, 11, 666, -1975)
t[3:] result is (11, 666, -1975)
t[1:4] result is (-3, 2, 11)
t[1::2] result is (-3, 11, -1975)
t[23] result is error
x in s
x not in s
s + t
s * n or n * s
len(s)
min(s)
max(s)
s.count(x)
s.index(x)
iterating over the elements :
for x in enumerate(mySequence) :
对x的操作
eg : l = [-2, 3, 11]
for x in l :
print(x**2)
iterate over the pairs(index, element)
for i, x in mySequence :
对x和i的操作
e.g. : str = "Alex is the best"
for index in range(len(str)) :
print(“The index : “, index, “and the letter is : “, str[index])
e.g. : str = "Alex is the best"
for index, letter in enumerate(str) :
print("The index :", index, "and the letter is :", letter)
lists
operations to edit a list :
s[i] = x
s[i:j] = t
del(s[i:j])
s[i:j:k] = t
del(s[i:j:k])
e.g. : myList = [1,2,3,4,5]
myList[2:3] = (6,’x’,7)
print(myList)
myList[1:6:2] = ‘sup’
print(myList)
processing operations :
list(s)
s.append(x)
s.extend(t)
s.insert(i,x)
s.clear()
s.remove(x)
s.pop(i)
s.reverse()
s.sort()
e.g. : myList = [1,3,5]
myList.append(7)
print(myList)
myList.extend((8,11))
print(myList)
myList.remove(8)
myList.insert(4,9)
print(myList)
strings(whose elements are characters and are not editable)
pay attention to the initialisation of multi-dimentional lists.
e.g. : board = [ [0]*3 for i in range(4)]
print(board)
board[3][2] = 666
print(board)
e.g. : board = [ [0]*3]*4
print(board)
board[3][2] = 666
print(board)
e.g. : board = [ [0]*3 for i in range (4)]
board[3][2] = 666
for ligne in board :
for x in ligne :
print(x, ‘ ‘, end = ‘ ‘ )
print(‘ ’)
N-tuples
note : you can not modify the elements of a t-tuple, delete, add others. a tuple passé
operation to create a tuple :
e.g. : myTuple = tuple(my Sequence) (turns a sequence into a tuple)
e.g. : myTuple = tuple(range(0, 9, 2))
myTuple
myTuple = tuple(“The Decemberist”)
myTuple
note : if we want to define a sequence of data that we do not want to change, use a tuple secure this. iterating over thhe elements of a t-tuple is a faster than those on a list. a function that returns “multiple values” actually returns a tuple.
a comment in python begins with “#”
from function import *(调用python的库函数)
from random import randint(调用randint)
how many bananas do you want to start with(add number required) 9
which player should start ? computer = (2), you = (1) 1
there are 9 bananas remaining
how many bananas do you want to take ? (1, 2 or 3)
3
player took 3 bananas.
computer took 3 bananas.
there are 3 bananas remaining
how many bans do you want to take ? (1, 2 or 3)
2
player took 2 bananas.
computer took 3 bananas.
game over
class and objects
learn how to declare a class
know how to built an object and initialise its attributes
be able to manipulate the class members according to their visibilities
declare a class
syntax : class className:
“ ” “ class documentation ” ” ”
we can access to the documentation of a class by the command : className.__doc__
to create an object of an existing class
syntax : myObject = className()
e.g. : class account:
“ ” ” management of a bank account ” ” ”
myAccount = account()
print(myAcccount)
print(myAccount.__doc__)
adding dynamic attributes:
syntax : myObject.myAttribute = value
e.g. : class account:
“ ” ” management of a bank account ” ” ”
myAccount = account()
myAccount.name = “PersonnalAccount”
myAccount.number = 666
myAccount.balance = -1000
declaration of methods within a class
syntax : class className:
“ “ “ class documentation “ “ “
def method1(self, para1, para2,…) :
…
def method2(self, para1, para2,…) :
…
note : self refer to the current object.
e.g. : class account:
“ “ “ management of a bank account “ “ “
def credit(self, x) :
self.balance += x
def showBalance(self):
print(“The balance is : “, self.balance)
myAccount = account( )
myAccount.name = >>PersonnalAccount”
myAccount.numbers = 6666
myAccount.balance = -1000
myAccount.credit(500)
myAccount.showBalance( )
declaration of a class method
syntax : class className:
“ “ “ class documentation “ “ “
@classmethod
def myClassMethod(cls, para1, …) :
…
eg :
access to a class method
syntax : myClass.myClassMethod(…)
syntax : anObject.myClassMethod(…)
e.g. : myAccount = account( )
account.numberAccount +=1
account.showNumberAccounts( )
myOtheraccount = account( )
account.numberAccount += 1
myOtheraccount.showNumberAccounts( )
constructors and destructors
the method <<__init_->>
syntax of the declaration of the method:
class className:
“ “ “ class documentation “ “ “
def __init__(self, para1, para2, …) :
…
def method1(self, para1, para2, …) :
…
eg :
default value of the attributes
e.g. : class account:
“ “ “ management of a bank account “ “ “
def __init__(self, name = “person”, number = 666, value = 1000):
self.name = name
self.number = number
self.balance = value
def showBalance(self) :
print( >>The balance is : “, self.balance)
myAccount = account(“pro”,777,10000)
myAccount.showBalance( )
myOtherAccount = account( )
my OtherAccount.showBalance( )
the method <<__del__>>
syntax of method declaration __del__ :
class className:
“ “ “ class documentation “ “ “
def __init__(self,para1,para2,…):
def __del__(self):
…
def method1(self,para1,para2,…):
…
encapsulation
syntax to declaw a private attributes :
def __init__(self, para1,para2,…):
publicAttribute = value
__privateAttribute = value
…
getter : a method returning the value of an attributes.
eg :
setter : a method fixing the value of an attribute.
eg :
中文海战游戏
game
-player1 : player
-player2 : player
-current : int
-hasWinner
+initiation
+changeTurn
+playOneTurn
+checkWinner
player
-playerBoard : pB
-historyBoard : hB
-name : str
-fleet : Fleet
+play()
+fire()
+
board
-list[ ][ ] : str
-
+draw()
+
boat
-letter : str
-state : int
-state : bool
-list[x,y]
+checkSpace
+sendPosition
+
fleet
-coordinate[(1,1),(1,2),(1,3),(1,4),(1,5)]
-
+
inheritance
simple inheritance
concept reminder
inheritance : relation of specialization/generalization between two classes. it indicate that a class named daughter class specialised another class called mother class, i.e. which own the same method and attributes of the mother class plus some which are its own.
general syntax
syntax of the declaration of an inheritance relationship :
class superClass:
“ “ “ a super class “ “ “
…
class subClass(superClass):
“ “ “ a subclass inheriting from the superclass” “ “
e.g. : class rectangle:
“ “ “ rectangle management “ “ “
…
class box(rectangle):
“ “ “ box management ” “ “
the protected visibility
public : attributes are accessible from anywhere.
private : attributes are accessible only within the class.
protected : attributes are limited to the class and its descendants.
syntax to declare an attribute protected :
during the implementation of the “__init__” method, we use a simple “_” before the name of the attribute:
def __init__(self,para1,para2,…):
publicAttribute = value
_protedtedAttribute = value
__privateAttribute = value
…
e.g. : class rectangle:
def __init__(self,x,y):
self._x = x
self._y = y
def surface(self):
return self._x*self._y
note : indeed, we will still be able to access the attribute from outside the class. in python, the declaration of a protected attribute with a visibility is only an indication towards the class users.
subclass constructor
first syntax : class subClass(superClass):
“ “ “ documentation of the subclass “ “ “
def __init__(self,para1,para2,…):
superClass.__init__(self,para1,…)
…
e.g. : a class box inheriting the previous rectangle class.
class box(rectangle):
def __init__(self,x,y,z):
rectangle.__init__(self,x,y)
self.__z = z
def volume(self):
return self._x*self._y*self.__z
photo = rectangle(3,4)
print(photo.surface())
weston = box(3,4,10)
print(weston.volume())
second syntax : class subClass(superClass):
“ “ “ documentation of the subclass “ “ “
def __init__(self,para1,para2,…):
super().__init__(para1,…) …
e.g. : class box(rectangle):
def __init__(self,x,y,z):
super().__init__(x,y)
self.__z = z
def volume(self):
return self._x*self._y*self._z
members transmission
back to the transmission of members(attributes and methods) according to their visibility.
e.g. : use of a public method of the parent class in the subclass.
class box(rectangle):
def __init__(self,x,y,x):
super().__init__(x,y)
self.__z = z
def volume(self):
return super().surface()*self.__z
e.g. : use of a public method of the parent class in the subclass.
class box(rectangle):
def __init__(self,x,y,z):
super().__init__(x,y)
self.__z = z
def volume(self):
return self.surface()*self.__z
e.g. : use of protected attributes of the superclass in the subclass.
class box(rectangle):
def __init__(self,x,y,z):
rectangle.__init__(self,x,y)
self.__z = z
def volume(self):
return self._x*self._y*self.__z
e.g. : impossible to use private attribute of the superclass in the subclass.
multiple inheritance
concept reminder
multiple inheritance : possibility for a class to have multiple superclass.
general syntax
syntax for the declaration of a multiple inheritance relationship :
class superClass1:
“ “ “ a super class “ “ “
class superClass2:
“ “ “ a super class “ “ “
class subClass(superClass1,superClass2,…):
“ “ “ a subclass inheriting from superClass1 and superClass2 “ “ “
e.g. : class carnivorous:
“ “ “ managements carnivorous “ “ “
…
class herbivorous:
“ “ “ managements of herbivorous “ “ “
class omnivorous(carnivorous,herbivorous):
“ “ “ management omnivores “ “ “
…
subclass constructor
note : the subclass constructor must make an explicit call to the manufacturers of mother classes to initialise the attributes inherited from them.
syntax of the constructor :
class subClass(superClass1,superClass2,…):
“ “ “ subclass documentation “ “ “
def __init__(self,para1,para2,…):
superClass1.__init__(self,para1,…)
superClass2.__init__(self,para1,…)
…
e.g. : class carnivorous:
def __init__(self,p):
self,_meatWeight = p
def nomNomNom(self):
print(<< I eat ”,self._meatWeight, << kg of stack everyday”)
class herbivorous:
def __init__(self,p):
self._herbWeight = p
def crunchCrunch(self):
print( << I eat “, self._herbWeight, << kg of herb everyday”)
e.g. : class omnivore(carnivorous,herbivorous):
def __init(self,mw,hw,h):
carnivorous.__init__(self,pv)
herbivorous.__init__(self,ph)
self.__human = h
eg : teddy = omnivore(10,5,False)
teddy.nomNomNom()
teddy.crunchCrunch()
search in the hierarchy
consider a multiple inheritance relationship type :
class subClass(superClass1,superClass2,superClass3…):
“ “ “ a subClass inheriting from superClass 2 and 3 “ “ “
…
note : if an object of class subClass called a method that does not belong to this class, the search will be from left to right in the list of parent classes. this means that we will look if the class “superClass1” has the method in question : if so, we apply this method and search is over. if not, consider the class “superClass2”.ect.
e.g. : class a:
“ “ “ a class a “ “ “
def example(self):
print(“I fount it in a”)
class b:
“ “ “ a class b” “ “
def example(self):
print(“I found it in b”)
class c(a,b):
“ “ “a class that inherits from c and b “ “ “
test = c()
test.example()
inheritance vs composition
the composition relationships
principle of composition relationship : it modelise an relationship between two instances of two classes. the object of the container class thus have an attribute that is an object of the contained class.
note : one can use a composition relationship between classes if you can establish a link of the type has or owns.
e.g. : a car has a license plate
a book owns pages.
a simple example
consider a class point with two attributes : abscissa(横坐标) ordinate(纵坐标)
we will then declare a class disk, which also possess two attributes : radius(a real number) center, which will be the object of class point.
e.g. : class point:
def __init__(self,x,y):
self.__x = x
self.__y= y
def getx(self):
return self.__x
def gety(self):
return self.__y
e.g. a disk class(圆类)
class disc:
def __init__(self,x,y,r):
self.__r = r
self.__center = point(x,y)
def surface(self):
return 3.14*self.__r**2
def getCenter(self):
return self.__center
cd = disc(-1,2,5)
print(“abscissa of the center:”, cd.getCenter().getx())
print(“ordinate of the center:”, cd.getCenter().gety())
note : abscissa is -1, ordinate is 2.
the inheritance in another way
in some cases it is quite possible technically to use composition relationship instead of an inheritance relationship. Instead of having a B class that inherits from a class A, we declare in b an attribute that will be an instance of class A.
Eg : class rectangle:
def __init__(self,x,y):
self.__x = x
self.__y = y
def surface(self):
return self.__x*self.__y
def getx(self):
return self.__x
def gety(self):
return self.__y
class boxBis:
def __init__(self,x,y,z):
self.base = rectangle(x.y)
self.__z = z
def volume(self):
return self.base.getx()*
self.base.gety()*self.__z
weston = boxBis(2,3,5)
print(Weston.base.surface())
print(Weston.volume())
note : the result is 6 and 30
what to choose?
The relationship between classes is in the shape like “is a “. The relationship between classes is of the form “a one”.
Note : you may also prefer a composition relationship in order to respect the principle of encapsulation. The relationship of composition is also easier to maintain in the event of changer to the code.
the concept of polymorphism
implement the polymorphism
adapt the usual operators to the classes that we are defining
present one of the flexibility of python : the duck typing
redefinition of the methods
concept reminder
polymorphism : mechanism that permit to a daughter class to redefine a method that she inherit ate from her mother class. this permit us to adapt the method’s treatment to the specification of the daughter class.
taking place
note : the polymorphism, i,e, the choice of the right method to use will automatically be made in function of object’s nature.
e.g. : class rectangle:
def __init__(self,x,y):
self._x = x
self._y = y
def surface(self):
return self._x*self._y
class paveDroit(rectangle):
def __init__(self,x,y,z):
super().__init__(x.y)
self.__z = z
def surface(self):
return 2*(self._x*self._y+self._x*self.__z+self._y*self.__z)
photo = rectangle(3,4)
print(photo.surface())
weston = paveDroit(3,4,10)
print(weston.surface())
operator overload
principle
when we create classes, it is natural to want to adapt the usual operators to be able to apply it on the objects.
when we say usual operators, we mean the logical and the arithmetic operators.
this creation of new version is called overload.
e.g. : for the class “rectangle”, we want for example, overload the “<” operator in order to classify the rectangles in function of the value of their surface.
or the “*” operator which will multiply the length and the width of the two rectangles in order to create a third one.
taking place
we will assume that the operator that we want to overload are like methods of the class.
the name of the method corresponding to an operator will be written like :
__NameOfTheOperator__
if the operator is unary(一元的),the method will only have the current object in a parameter.
e.g. : def __NameOfTheOperator__(self):
…
if the operator is binary, the method will have the current object in a parameter and another object.
e.g. : def __NameOfTheOperator__(self,other):
…
operators arithmetics :
+ : __add__(self,other)
- : __sub__(self,other)
* : __mul__(self,other)
/ : __dv__(self,other)
// : __floordiv__(self,other)
% : __mod__(self,other)
** : __pow__(self,other)
+= : __iadd__(self,other)
-= : __isub__(self,other)
*= : __imul__(self,other)
/= : __idiv__(self,other)
//= : __ifloordiv__(self,other)
%= : __imod__(self,other)
**= : __ipow__(self,other)
some unary operators :
- : __neg__(self)
abs() : __abs__(self)
bin : __bin__(self)
oct : __oct__(self)
hex : __hex__(self)
logical operator :
< : __lt__(self,other)
<= : __le__(self,other)
> : __gt__(self,other)
>= : ge__(self,other)
== : __eq__(self,other)
!= : __ne__(self,other)
examples
e.g. : overload of the operator * and *=
class rectangle:
def __init__(self,x,y):
self.__x = x
self.__y = y
def surface(self):
return self.__x*self.__y
def __mul__(self,other):
return rectangle(self.__x*other.__x,self._y*other.__y)
def __imul__(self,other):
self= self*other
return self
a = rectangle(3,4)
b = rectangle(2,5)
c = a*b
print(c.surface())
c *= b
print(c.surface())
note : the result is 120 and 1200.
e.g. : overload of the operator < and ==
class rectangle:
def __init__(self,x,y):
self.__x = x
self.__y = y
def surface(self):
return self.__x*self.__y
def __lt__(self,other):
return self.surface() < other.surface()
def __eq__(self,other):
return self.__x == other.__x and self.__y == other.__y
a = rectangle(3,4)
b = rectangle(2,7)
print(a <b)
print(a == b)
note : the result is true and false.
exercise
in pycharm
the duck typing
principle
in python we don’t specify the type waited by the functions’ parameters(resp. method)
that imply that we can use a function with any type, with the condition that the operators of the function(resp.method) are compatible with the types of the parameters.
then, we care more about the behaviour of an object than his type.
if the method of an object are compatible with the requiree function’s operators, then the function can be apply on the object.
example
e.g. : class rectangle:
def __init__(self,x,y):
self.__x = x
self.__y = y
def surface(self):
return self.__x*self.__y
class disc:
def __init__(self,r):
self.__r = e
def surface(self):
return 3.14*self.__r**2
def painting(object):
return 2*object.surface()
cd = disc(10)
photo = rectangle(20,15)
print =(painting(cd))
print(painting(photo))
12.9 16.00-19.00 —> exercise