Learn Programming in OOP with Examples

in #utopian-io7 years ago (edited)

oop.jpg
Image Source

What Will I Learn?

This post constitutes the "course" programming with python. Although out program, this document may be of interest to students of the specialty ISN terminal, in particular when carrying out projects.

Requirements

Download Python from https://www.python.org/downloads/

Difficulty

  • Intermediate

Tutorial Contents


Object Oriented Programming (OOP)

Object-Oriented Programming is a Modern Programming Method Extremely powerful.
In everyday life, we are surrounded by objects (by object I hear all things inanimate, but also living beings!). The idea of ​​object-oriented programming is to manipulate elements that are called "objects" in its source code.
An object in everyday life, you know, but in computer science, what is it?
A variable ? A function?
Neither. It's a new element in programming.
To be more precise, an object is a mixture of several variables and functions!
Imagine an object (of everyday life) very complex (eg a car enginefor a layperson):
It is obvious that looking at this object, we are struck by its complexity (for a non specialist).
Imagine that you lock this object in a box and that the user of the object does not need to know its internal operating principle to be able to use it. The user has, at his provision, 2 buttons and a joystick to operate the object, which makes its use relatively simple.

The development of the object (by engineers) has been very complex, but its use is relatively simple.
Programming in an object-oriented way is creating source code (which can be complex), but that one masks by placing it inside a cube (an object) through which one sees nothing. For the programmer who will use a class coded by another programmer, work with an object So it's much simpler than before: it just has to press buttons and does not need to be engineer to use it.

One of the many benefits of OOP is that today there are thousands of objects (they are called classes) ready to be used. We can realize programs extremely complex only by using pre-existing classes (objects). Of course, we will also create our own classes in python.


OOP and python

Creating a class in python always starts with the word class. Then all instructions from the class will be indented:

class theNameMyClass (object):
class instructions

The definition of the class is complete.

The class is a kind of mold (we will return later to this analogy which has its limits), to from this mold we will create objects (more exactly we will talk about instances). By example we can create a car class and then create different instances of this class (Peugeot407, RenaultEspace, ........). To create one of these instances, the procedure is relatively simple:
Peugeot 407 car = ()

This line simply means: "create an object (an instance) of the class car that one will appoint Peugeot407. "
Then, nothing prevents us from creating a second instance of the class car:
Renault Espace car = ()
Here we meet the limit of our analogy with the mold. Indeed 2 objects made with the same mold will be (definitely) identical, whereas here our 2 instances may have "a destiny " very different.
To develop all these notions (and others), we will write a little program (without any claim):
We will start by writing a class "character" (which will initially be a shell empty) and, from this class create 2 instances: Bilbo and Gollum.
Example1:

# Define a character class
character class (object):
 #For the moment this class is an empty shell, but as it must contain a
#instruction we put the pass instruction that does nothing!
 pass
# we create an instance of the character class named Gollum (we come back to the line because the
# class definition is complete)
Gollum character = ()
# we create another instance of the character class named Bilbo
Bilbo character = ()

As explained above, a class instance has attributes (variables) and methods (functions). Let's start with the attributes:
We will associate a life attribute with our character class (each instance will have a life attribute, when the value of life becomes null, the character will be dead!)
These attributes are used as variables, the attribute life for Bilbo will be noted bilbo.vie, of the
similarly the life attribute of the Gollum instance will be noted gollum.vie.

Example2:

# Define a character class
character class (object):
 pass
# we create an instance of the character class named Gollum
Gollum character = ()
# Gollum is given 20 life by creating an attribute (variable in a class) life for
# the Gollum instance
gollum.vie = 20
# we created another instance of the character class named Bilbo
Bilbo character = ()
# Give Bilbo 20 life
bilbo.vie = 20
#display of health points for Bilbo
print ('Bilbo a', bilbo.vie, 'points of life')
#display of health points for Gollum
print ('Gollum a', gollum.vie, 'points of life')
print ('Bilbo is injured by Gollum')
#Bilbo is injured, he loses a point of life
bilbo.vie = bilbo.vie-1
#on show again life points
print ('Bilbo a', bilbo.vie, 'points of life')
print ('Gollum a', gollum.vie, 'points of life')
A2
Bilbo has 20 life.
Gollum has 20 life.
Bilbo is injured by Gollum
Bilbo has 19 points of life
Gollum has 20 life.

All this is beautiful, but not very "clean", and this way of programming would draw up the hair on the head of any seasoned programmer!
Indeed, we do not respect a basic principle of OOP: encapsulation We must not forget that our class must be "locked in a box" so that the user can use it easily without worrying about what's going on inside, out, here it's not really the case.

In fact, the attributes (gollum.vie and bilbo.vie) belong to the class and should therefore be locked in the box! What are they doing outside the definition of class then?
To solve this problem, we will define the attributes, in the class, using a method (a method is a function defined in a class) initialization of attributes.
This method is defined in the source code by the line "def __init__ (self)" (the word self is necessarily the first argument whatever the method). We find this word self when defining the attributes (the definition of the attributes will be of the form "self.vie = 20")
The presence of this word self is quite complicated to explain. Basically, the word self represents the instance. When you define a class instance (bilbo or gollum) the name of your instance will replace the word self.

In the source code we will have:

Class character (object):
def __init__ (self):
self.vie = 20
#class end

Then when creating the gollum instance, python will automatically replace self by gollum and thus create a gollum.vie attribute which will have as starting value the value given to self.vie in the __init__ method (in our example 20) It will happen exactly the same thing at the time of the creation of the instance bilbo, one will have automatically creating the attribute bilbo.vie.

Example3

# Define a character class
character class (object):
 # we define the method that will initialize the attributes
 def __init __ (self):
 self.vie = 20
# we create an instance of the character class named Gollum
Gollum character = ()
# we create another instance of the character class named Bilbo
Bilbo character = ()
#display of health points for Bilbo
print ('Bilbo a', bilbo.vie, 'points of life')
#display of health points for Gollum
print ('Gollum a', gollum.vie, 'points of life')
print ('Bilbo is injured by Gollum')
#Bilbo is injured, he loses a point of life
bilbo.vie = bilbo.vie-1
#on show again life points
print ('Bilbo a', bilbo.vie, 'points of life')
print ('Gollum a', gollum.vie, 'points of life')
A3

The result of Example 3 is obviously identical to the result of Example 2. But this time we did not set the attribute 'gollum.vie = 20 and bilbo.vie = 20 outside the class we used a init method.
The init method is a function (more exactly a method, but we saw that it was the same thing), like all functions we can pass parameters to it as a variable (as already seen before with the functions).
The parameter passing is done at the moment of creation of the instance, still a small example to clear up all this:

Bilbo has 20 life.
Gollum has 20 life.
Bilbo isv injured by Gollum
Bilbo has 19 points of life
Gollum has 20 life.

The result of Example 3 is obviously identical to the result of Example 2. But this time we did not set the attribute 'gollum.vie = 20' and bilbo.vie = 20 outside the class we used a 'init method'.
The 'init 'method is a function (more exactly a method, but we saw that it was the same thing), like all functions we can pass parameters to it as a variable (as already seen before with the functions).

Example4
character class (object):

 #on defines the method that will initialize the attributes, it now has a
# additional parameter.
 def __init __ (self, number of Life):
 # the self.vie attribute is initialized with the value of
 self.vie = nbreDeVie
# create an instance of the character class named Gollum and initialize the variable
#LastNumber with value 20
Gollum character = (20)
# we create another instance of the character class named Bilbo and initialize the variable
#LastNumber with value 20
Bilbo character = (20)
#the rest of the code remains the same
print ('Bilbo a', bilbo.vie, 'points of life')
print ('Gollum a', gollum.vie, 'points of life')
print ('Bilbo is injured by Gollum')
bilbo.vie = bilbo.vie-1
print ('Bilbo a', bilbo.vie, 'points of life')
print ('Gollum a', gollum.vie, 'points of life')
A4
Bilbo has 20 life.
Gollum has 20 life.
Bilbo is injured by Gollum
Bilbo has 19 points of life
Gollum has 20 life.
Some explanations are needed:

At the moment of the creation of the gollum instance, we pass as an argument the number of lives (gollum = character (20)). This number of lives is attributed to the first argument of the method init, the variable numberLife (lifetimeNumber is not quite the first argument of the method init since before there is self, but hey, self being obligatory, we can say that firstNumber is the first non-mandatory argument).

Then, we assign the value contained in the variable NbromeValue to the attribute self.vie (line self.vie = number of Life)
NB: I'm talking about variable for nbreDeVie (because it's not an attribute of the character class since it does not start with self).
Of course, we can pass several arguments to the init method (like any function), we will see examples in a moment. It's already better, but not everything is perfect yet. Indeed, we still see ourselves "wandering" "gollum.vie" outside the classroom (especially in gollum.vie = gollum.vie-1 or
lines that display the number of lives remaining), which is still problem with encapsulation.

To solve this problem, we will create 2 new methods:
  • A method that will remove a hit point from the injured character
  • A method that will display the number of lives remaining

Let's look at example 5 how to achieve our goals (be careful, there will be a lot of new stuff), we will take the opportunity to pass several arguments to the method init.

Example5

# Defines a class
character class (object):
 # method __init__ with 2 arguments (not counting self!) the number of lives and the name of the
#character
 def __init __ (self, lifetimeNumber, namePerso):
 self.vie = nbreDeVie
 self.nom = nomDuPerso
 # here is the method that displays the state of the character (be careful to put the argument well
#self, it is obligatory.
 def posterState (self):
 print ('It remains', self.vie, 'life points to', self.name)
 # here is the method that causes the life of an attacker to lose 1 life
 def perdVie (self):
 print (self.name, 'suffer an attack, he loses a life')
 self.vie = self.vie-1
#the "manufacture" of the class is over, the rest of the program is only composed of
# creation of instances and method invocation
#on create the gollum instance without forgetting to pass the number of health points and the name of the
#character
Gollum character = (20 'Gollum')
# we call the stateState method for the gollum instance
gollum.afficheEtat ()
Bilbo = character (20 'Bilbo')
#we call the posterState method for the bilbo instance
bilbo.afficheEtat ()
#one calls the perdVie method for the bilbo instance
bilbo.perdVie ()
#re calls the stateRepresent method for the gollum instance again
gollum.afficheEtat ()
#et for the bilbo instance
bilbo.afficheEtat ()
A5
Gollum has 20 points of life
Bilbo has 20 life points
Bilbo suffers an attack, he loses a life
Gollum has 20 points of life
Bilbo has 19 life points
Inheritance concept in OOP

To finish with objects, we still have an important concept to address: inheritance.
We will create a new class (the magician class) that will inherit the character class (we will say that the magician class will be the class girl and character will be the parent class).
For once, this term of inheritance is well suited to the situation. Indeed the magician class is going inherit all the methods and attributes of the character class (an attribute of magician will have a name and health points, such as a character attribute, and will be able to use the methods of the character class). So what is the point of creating a new class? Well, the magician instance will have an additional attribute (magicMagic) and a method additional (launchDesSorts). In all, a magician instance will have 3 attributes (2 inherited from the character class (life and name) and 1 of its own (magicMagic)) and 3 methods (2 inherited from the character class and 1 own) The establishment of the inheritance is very simple, since it is enough to replace object by the name of the parent class, in our example we will define the wizard class as follows:
class magician (character)

Example6

character class (object):
 # method __init__ with 2 arguments (not counting self!) the number of lives and the name of the
#character
 def __init __ (self, lifetimeNumber, namePerso):
 self.vie = nbreDeVie
 self.nom = nomDuPerso
 # here is the method that displays the number of lives of the character.
 def affichePointVie (self):
 print ('It remains', self.vie, 'life points to', self.name)
 # here is the method that causes the character who has been attacked to lose 1 life
 def perdVie (self):
 print (self.name, 'suffer an attack, he loses a life')
 self.vie = self.vie-1
#the wizard class inherits the character class
class magician (character):
 #In def_init_ we find nbreDeVie and nomDuPerso as in the def __init__ of the
#personal class
 def __init __ (self, lifetimeNumber, namePerso, pointMagic):
 #the next line is very important in the case of inheritance, it is necessary
 # systematically make this kind of call:
 #classeparente .__ init __ (self, arg1, arg2 .....)
 character .__ init __ (self, number of Life, name of Perso)
#character
 self.magie = pointMagie
 #a class only available for magician instances
 def doMagie (self):
 print (self.name, 'do magic')
 self.magie = self.magie-1
 def affichePointMagie (self):
 print (self.name, 'a', self.magie, 'magic points')
 #the other methods of the magician instances are inherited from the character class
#on create a magician instance
gandalf = wizard (20 'Gandalf', 15)
#apply the methodPlayPointPage to gandalf, this method is inherited from the character class
gandalf.affichePointVie ()
gandalf.affichePointMagie ()
#apply the makeMagie method to gandalf, this method is only applicable to instances
#of the magician class
gandalf.faireMagie ()
gandalf.affichePointMagie ()
A7
l remain 20 points of life in Gandalf
Gandalf has 15 magic points
Gandalf does magic
Gandalf has 14 magic points



Posted on Utopian.io - Rewarding Open Source Contributors

Sort:  

Your contribution cannot be approved because it does not follow the Utopian Rules.

  • It has a lot of errors. The programs that you have provided will NOT WORK !

You create a class and define the instance. But when you define the attributes you Capitalize the instance name.

Their are multiple such errors. In fact, it appears that the tutorial originated in a different language (french, as the last code box contains french.) and this tutorial is a simple translation and copy paste of the same.

You can contact us on Discord.
[utopian-moderator]

Congratulations @holudghuri! You have completed some achievement on Steemit and have been rewarded with new badge(s) :

Award for the number of posts published

Click on any badge to view your own Board of Honor on SteemitBoard.
For more information about SteemitBoard, click here

If you no longer want to receive notifications, reply to this comment with the word STOP

By upvoting this notification, you can help all Steemit users. Learn how here!

Coin Marketplace

STEEM 0.19
TRX 0.18
JST 0.035
BTC 90928.46
ETH 3207.56
USDT 1.00
SBD 2.81