Installation of python on a Windows OS is similar to the installation of any other package. Download the executable file from https://www.python.org/downloads/.
- Adding to path If you open the command prompt and type python, a less-than-friendly error is thrown stating that no package like that can be found. To fix this however, we should add the location to the system path. Click on Control Panel → System → Advanced → Environment Variables. Click on the variable named PATH in the System Variables section, then select Edit and add ;C:\Python27 (please verify that this folder exists.
On Mac and GNU/Linux distributions, python should come pre-installed. To check if python is installed on Ubuntu, open the terminal (You can type Ctl + Alt + T). Type this command on the terminal which python.
Python is a language with a simple synthax. It is both easy to read and easy to write. Awareness for python is increasing on a daily basis because of the speed of implementation. It's application cuts accross several operations like data analysis, video gaming, web programming, and even machine learning. It's open source nature and portability makes it usable on different platforms.
Python is a simple to write and understand language. Reading Python feels like reading English. In fact Peter Norvig, a well-known Lisp author and Director of Search Quality at Google, iterated that python feels like writing pseudocodes. Because of some of these qualities of python it recently, in a survey done by Stackoverflow overtook languages like Php as the third most preferred language by developers only trailing the likes of javaScript and PhP. In this section of python baics, we will look at some of the qualoities of the language which includes but are not limited to Extensibility, FLOOS etc.
Python is one of those rare languages which can claim to be both simple and powerful. You will find yourself pleasantly surprised to see how easy it is to concentrate on the solution to the problem rather than the syntax and structure of the language you are programming in.
The official introduction to Python is:
Python is an easy to learn, powerful programming language. It has efficient high-level data structures and a simple but effective approach to object-oriented programming. Python’s elegant syntax and dynamic typing, together with its interpreted nature, make it an ideal language for scripting and rapid application development in many areas on most platforms.
-
Simple
Python is a simple and minimalistic language. Reading a good Python program feels almost like reading English, although very strict English! This pseudo-code nature of Python is one of its greatest strengths. It allows you to concentrate on the solution to the problem rather than the language itself. -
Easy to Learn
As you will see, Python is extremely easy to get started with. Python has an extraordinarily simple syntax, as already mentioned. -
Free and Open Source
Python is an example of a FLOSS (Free/Libré and Open Source Software). In simple terms, you can freely distribute copies of this software, read its source code, make changes to it, and use pieces of it in new free programs. FLOSS is based on the concept of a community which shares knowledge. This is one of the reasons why Python is so good - it has been created and is constantly improved by a community who just want to see a better Python. -
High-level Language
When you write programs in Python, you never need to bother about the low-level details such as managing the memory used by your program, etc. -
Portable
Due to its open-source nature, Python has been ported to (i.e. changed to make it work on) many platforms. All your Python programs can work on any of these platforms without requiring any changes at all if you are careful enough to avoid any system-dependent features. You can use Python on GNU/Linux, Windows, FreeBSD, Macintosh, Solaris, OS/2, Amiga, AROS, AS/400, BeOS, OS/390, z/OS, Palm OS, QNX, VMS, Psion, Acorn RISC OS, VxWorks, PlayStation, Sharp Zaurus, Windows CE and PocketPC! You can even use a platform like Kivy to create games for your computer and for iPhone, iPad, and Android. -
Interpreted
This requires a bit of explanation. A program written in a compiled language like C or C++ is converted from the source language i.e. C or C++ into a language that is spoken by your computer (binary code i.e. 0s and 1s) using a compiler with various flags and options. When you run the program, the linker/loader software copies the program from hard disk to memory and starts running it. Python, on the other hand, does not need compilation to binary. You just run the program directly from the source code. Internally, Python converts the source code into an intermediate form called bytecodes and then translates this into the native language of your computer and then runs it. All this, actually, makes using Python much easier since you don’t have to worry about compiling the program, making sure that the proper libraries are linked and loaded, etc. This also makes your Python programs much more portable, since you can just copy your Python program onto another computer and it just works! -
Object Oriented
Python supports procedure-oriented programming as well as object-oriented programming. In procedure-oriented languages, the program is built around procedures or functions which are nothing but reusable pieces of programs. In object-oriented languages, the program is built around objects which combine data and functionality. Python has a very powerful but simplistic way of doing OOP, especially when compared to big languages like C++ or Java. -
Extensible
If you need a critical piece of code to run very fast or want to have some piece of algorithm not to be open, you can code that part of your program in C or C++ and then use it from your Python program. -
Embeddable
You can embed Python within your C/C++ programs to give scripting capabilities for your program’s users. -
Extensive Libraries
The Python Standard Library is huge indeed. It can help you do various things involving regular expressions, documentation generation, unit testing, threading, databases, web browsers, CGI, FTP, email, XML, XML-RPC, HTML, WAV files, cryptography, GUI (graphical user interfaces), and other system-dependent stuff.
Enough of all the theories and let's get started with coding. Just like in every other programming course, our aim is to print a message to the console. Open command prompt in Windows or terminal in Mac/Linux and type python (if you get any errors, check the series on how to add python to your system PATH). You should be taken to an environment where you these 3 greater-than symblols (>>>). Type the next command print("Hello World!").
While building a web app or developing a vidoe game or any other application of sort, we need a way to prompt users for inputs and perform several operations with those input. These input are stored in containers known as variables. Python variables are made of four major types, leaving out the assorted ones list the lists and dictionaries.
- Boolean
Booleans are list light switches; they have only two states-- on and off --which are True and False.
Example:
is_true = True
is_false = False
print (type(is_true), type(is_false))The ouput of this code is:
(<type 'bool'>, <type 'bool'>)
-
String Our names are examples of variables of type string. Strings have values that are quoted with single or double quotation marks. As an example let's declare a variable name with the value of "Olalekan Babawale".
-
Integer
integers are whole numbers without fractional parts. Examples of integers are 1, 2, 4 etc. Example:
age = 21
print(type(age))The code above outputs
<type 'int'>.
- Float
Floating point numbers are numbers with fractional parts such as 17.90, 8.32, 0.12 etc.
Example:
staff_wage = 234.56
print (type(staff_wage))outputs <type 'float'>
- None
None is a type in Python used to indicate that a variable has no value. This is hardly popular but is still a very important feature of the language. It's can be used to pass a default value as an argument to a function upon which to perform some logic. Example:
name = None
print(type(name))outputs <type 'NoneType'>
While the code tells us 'how', it is the comments that we put in the code that explain why. Commenting is a good attribute of a developer because it expalins to the reader the function of your code even before they are able to absorb the details of the code itself. In practice, this saves the reader (and the reader might even be you).
- Single-line Comments
Single-line comments are used to write short notes in the code which do not go beyond a line. Single-line comments are prepended with a (#) symbol as shown in the code below:
# I am a single line comment
print ("Hello world!") # And I am also a single-line comment
- Multi-line comments
These are used to add comments usually exceeding a line into our code. The comments are enclosed between a pair of three single or double quotation marks on each side.
'''
The way python used the multi-line comments is so fascinating
I cant stop loving it.
Would you rather come along?
'''
def comments():
"""
Even inside a function block,
it works well.
"""
passPython is indeed an exciting and powerful language. It has the right combination of performance and features that make writing programs in Python both fun and easy.
Most statements (logical lines) that you write will contain expressions. A simple example of an expression is 2 + 3. An expression can be broken down into operators and operands.
Operators are functionality that do something and can be represented by symbols such as + or by special keywords. Operators require some data to operate on and such data is called operands. In this case, 2 and 3 are the operands. Python has a wide range of operators but we will consider only a few important ones.
Here is a quick overview of the available operators:
+ (plus)
Adds two objects
3 + 5 gives 8. 'a' + 'b' gives 'ab'.
- (minus)
Gives the subtraction of one number from the other; if the first operand is absent it is assumed to be zero.
-5.2 gives a negative number and 50 - 24 gives 26.
* (multiply)
Gives the multiplication of the two numbers or returns the string repeated that many times.
2 * 3 gives 6. 'la' * 3 gives 'lalala'.
** (power) Returns x to the power of y 3 ** 4 gives 81 (i.e. 3 * 3 * 3 * 3)
/ (divide) Divide x by y 13 / 3 gives 4. 13.0 / 3 gives 4.333333333333333
% (modulo) Returns the remainder of the division 13 % 3 gives 1. -25.5 % 2.25 gives 1.5.
< (less than)
Returns whether x is less than y. All comparison operators return
True or False.
Note the capitalization of these names.
5 < 3 gives False and 3 < 5 gives True.
Comparisons can be chained arbitrarily:
3 < 5 < 7 gives True.
> (greater than) Returns whether x is greater than y 5 > 3 returns True. If both operands are numbers, they are first converted to a common type. Otherwise, it always returns False.
<= (less than or equal to) Returns whether x is less than or equal to y x = 3; y = 6; x # y returns True.
>= (greater than or equal to) Returns whether x is greater than or equal to y x = 4; y = 3; x >= 3 returns True.
== (equal to) Compares if the objects are equal x = 2; y = 2; x == y returns True. x = 'str'; y = 'stR'; x == y returns False. x = 'str'; y = 'str'; x == y returns True.
!= (not equal to) Compares if the objects are not equal x = 2; y = 3; x != y returns True.
not (boolean NOT) If x is True, it returns False. If x is False, it returns True. x = True; not x returns False.
and (boolean AND) x and y returns False if x is False, else it returns evaluation of y x = False; y = True; x and y returns False since x is False. In this case, Python will not evaluate y since it knows that the left hand side of the 'and' expression is False which implies that the whole expression will be False irrespective of the other values. This is called short-circuit evaluation.
or (boolean OR) If x is True, it returns True, else it returns evaluation of y x = True; y = False; x or y returns True. Short-circuit evaluation applies here as well.
Ternary operator
Python also has what we call ternary operator. The ternary operation is an if ... else block except that the expression is written on a line.
For instance we want to assign wear to trousers if sex is male otherwise wear is skirt.
sex = "Male"
wear = "Trousers" if sex == "Male" else "Skirt"
print(wear)The output of the code is Trousers. If we change the sex to Female, the output becomes Skirt.
Python has a built in order of executing python expression. however we won't be treating that in this course. To get the official reference material documenting the order of precedence, follow this link.
We have been using expressions since we started this course. What are expressions? Let's say we have a need to find the area of a rectangle with length 2cm and breadth 4cm. We can go on to perform an operation on the operands using a multiplication (*) operator and thus assigning the output to a variable called area. This is an expression.
length = 2
breadth = 3
area = length * breadth # this is an expression We will use expressions throughout our use interaction with python.
- If statement
We often want to perform an action only after we have checked for a condition, 'If' statements come in handy in such situations. The basic synthax of the if statement is
if <condition>:
<action_to_perform>Example:
name = "Olalekan"
if name == "Olalekan":
print ("He's definitely a man!")- If/Else Statements In the last example, we perform an action if our search condition is met, otherwise nothing happens. We oftem want to perform a different action if our test condition is not met. And that is where our If/Else statements play a vital role. The basic structure is:
if <condition>:
<perform_action>
else:
<perform_another_action>An example if to a code that prints out if a child is eligible for university based on if s/he is up to 18 years old.
# This code checks if child is eligible for university
age = 17
if age < 18:
print("You're not eligible for university!")
else:
print("Congrats, you can enroll in the university")And this code outputs You're not eligible for university!
- If/Elif/Else Statements
The If/Elif/Else blocks allow us to check several conditions and perform specific actions based on any of them. We will get the idea better with the use of an example.
years_of_service = 23
if years_of_service < 10:
print("Young employee")
elif years_of_service < 20:
print("Intermediate employee")
else:
print("Old employee")The code outputs Old employee
- While expression
Example:
number = 20
while number > 0:
print "{num} is greater than 0".format(num=number)
number -= 1the output of this is:
20 is greater than zero
19 is greater than zero
18 is greater than zero
17 is greater than zero
16 is greater than zero
15 is greater than zero
14 is greater than zero
13 is greater than zero
12 is greater than zero
11 is greater than zero
10 is greater than zero
9 is greater than zero
8 is greater than zero
7 is greater than zero
6 is greater than zero
5 is greater than zero
4 is greater than zero
3 is greater than zero
2 is greater than zero
1 is greater than zero
- For Loop
The for loop statement is used to perform iteration over a range of values. The loop repeats till the a termination point is reached. For our example we'll consider the for loop with a range method. create a python file called for.py and add the following block of code to it.
for i in range(1, 5):
print("{}".format(i))The code produces an output of
1
2
3
4
Now let's expalain this a little bit. The range() method takes two arguments: the lower bound and the upper bound and generates a list of contiguous values. In our example, the range statement produces a list equivalent to this [1, 2, 3, 4]. So the for statement iterates over the list and prints out each of the items in it.
Continue statement The continue statement is used to skip a loop action for a particular criterium. Let's reconsider our last for loop example. Let's skip printing the number three(3). The code looks like this:
for i in range(1, 5):
if i == 3:
continue
print("{}".format(i))3 is skipped in the output.
1
2
4
Break statement The break statement is used to exit a loop prematurely. If in our loop example we want to break out of the loop once we find the number 2, we can introduce a break statement in our code. We tweak the code a little to ensure we print 2 as the last number.
for i in range(1, 5):
print("{}".format(i))
if i == 2:
breakand the output of this is:
1
2
Functions are reusable pieces of programs. They allows us to give a name and encapsulate a block of statements*(codes)*, allowing us to run that block using the specified name anywhere in the program and any number of times.
The function concept is probably the most important building block of any non-trivial software (in any programming language).
Functions are defined using the def keyword. After this keyword comes an identifier name for the function, followed by a pair of parentheses which may enclose some names of variables, and by the final colon that ends the line. Next follows the block of statements that are part of this function.
Example:
def employee():
"""Return profile of an an employee"""
pass # But this does nothing now.From the block of codes, we define a function called employee using the syntax as explained above. This function takes no parameters (some people called this arguments, but the real name is parameter) and hence there are no variables declared in the parentheses.
Parameter is an input variable to functions or procedure definition, that gets an actual value(argument) at execution time.
They are just input to the function so that we can pass in different values to it and get back corresponding results. Notice that we can call the same function twice which means we do not have to write the same code again.
A function can take zero or as many parametes as needed, which value(s) would be supplied to the function at run time(during execution), the function can then do something using those values.
These parameters are just like regular variables except that thier values were defined when we call the function and are already assigned values when the function runs.
Parameters are specified within the pair of parentheses in the function definition, separated by commas. When we call the function, we supply the values in the same way.
Note the terminology used - the name of variables given in the function definition are called parameters whereas the values you supply in the function call are called arguments.
Example:
# definition of a function maximum.py
def maximum(a, b):
"""Return the greater number between a and b"""
if a > b:
print a, 'is greater than', b
elif a == b:
print a, 'and b are equal'
else:
print b, 'is greater than', a
# Now let us call the our maximum function, by passing value to it directly.
maximum(6, 4) # -> 6 'is greater than', 4
# we can also pass variable as an arguments, which is what we will do almost everytime.
x = 15
y = 17
arguments(x, y) # -> 17, 'is greater than', 15From the above code block, we define a function called maximum that accept two posotional arguments , i.e parameter a and b . We then find out the greater number using a simple if..else statement and then print the bigger number.
When ever we declared any variable inside a function definition, such variable has no relationship with other variable of the same name declared outside the function block, i.e. variable names are local to the function.
This is called the scope of the variable. All variables have the scope of the block they are declared in, starting from the point of definition of the name.
# employee.py
name = 'babatope ajepe'
def employee(name):
"""Return profile of an an employee"""
print 'name is', name
name = 'john doe'
print 'name is now change to', name
# output
employee(name) # -> name is babatope ajepe
# -> name is now changed to john doe
print name # -> babatope ajepe The first time that we print the value of the name name with the first line in the function’s body/block, Python uses the value of the parameter declared in the main block, above the function definition.
Next, we assign the value 'john doe' to name . The variable name name is local to our function. So, when we change the value of name in the function, the name defined in the main block remains unaffected.
The last print statement display the value of name as defined in the main block(global scope), confirming that it is actually unaffected by the local assignment within the previously called function.
If we want to re-assign or change the value to a name declared at the top level of the program, with our employee function. We need to tell Python that the variable is not local, but it is global.
We can do this using the global statement. Practically, It is impossible to re-assign a value to a variable defined outside a function without the use global statement. Using the global statement makes it amply clear that the variable is defined in an outermost block.
Example:
# employee.py
name = 'babatope ajepe'
def employee(name):
"""Return profile of an an employee"""
global name # referencing the global name outside the employee scope.
print 'name is', name
name = 'john doe'
print 'name is now change to', name
# output
employee(name) # -> name is babatope ajepe
# -> name is now changed to john doe
print name # -> john doeThe use of the global statement, tells Python that the variable name is a global variable i.e (outside the local scope) hence, when we re-assign a value to name inside the employee function*(local scope)*, that change the value of name in the global scope.
For some functions, we may want to make some parameters optional and use default values in case the user does not want to provide values for them. This is done with the help of default argument values. we can set default argument values for parameters by appending to the parameter name in the function definition the assignment operator ( = ) followed by the default value. Note that the default argument value should be a constant. More precisely, the default argument value should be immutable.
def warning(message, times=1):
"""warn a friend about danger ahead, in number of times."""
print message * times
warning("Don't play with python, it's very dangerous") # -> Don't play with python, it's very dangerous
warning("Don't play with python, it's very dangerous", 2) # -> Don't play with python, it's very dangerous
# -> Don't play with python, it's very dangerous The function named warning is used to print a string as many times as specified. If we don’t supply a value, then by default, the string is printed just once. We achieve this by specifying a default argument value of 1 to the parameter times.
In the first usage of warning , we supply only the string and it prints the string once. In the second usage, we supply both the string and an argument 2 stating that we want to say the string message two times.
Key worded arguments are **kwargs are mostly used in function definitions in Odoo. *args and **kwargs allow us to pass a variable number of arguments to a function. What variable means here is that we do not know beforehand how many arguments can be passed to our function by the user. *args is used to send a non-keyworded variable length argument list to the function. Example:
def accumulate(exam_score, *test_scores):
print "first normal arg:", exam_score
for test_score in test_scores:
print "another arg through *test_scores:", test_score
accumulate(50, 16, 15)The accumulate function, accept one formal positional arguent and the followed by now-keyword arguments(**arg), this enables us to call the function with an unlimited number of now-keyword argument.
**kwargs allows us to pass keyworded variable length of arguments to a function. Let say we want to handle named arguments, we should use **kwargs in the function. Example:
def greet_me(**kwargs):
for key, value in kwargs.items():
print("{0} = {1}".format(key, value))
greet_me(name="Ajepe babatope") # -> name = Ajepe babatopeThe return statement is used to return from a function i.e. break out of the function. We can optionally return a value from the function as well.
def maximum(a, b):
"""Return the maximum number between a and b."""
if a > b:
return a # The execution will break here if a > b
elif a == b:
return 'the numbers are equal' # or here if a == b
else:
return b # and if b > a it will break here.
print maximum(2, 2) # -> the numbers are equalThe maximum function returns the maximum of the parameters, in this case the numbers supplied to the function. Note that a return statement without a value is equivalent to return None . None is a special type in Python that represents nothingness. For example, it is used to indicate that a variable has no value if it has a value of None.
We have seen so covered many aspects of python functions, that woud=ld be needed for Odoo day to day development, but note that we still haven’t covered all aspects of them.
You have seen how we can reuse our code in any program by defining functions once. What if we wanted to reuse a number of functions in other programs?
As you might have guessed, the answer is modules. There are various methods of writing modules, but the simplest way is to create a file with a .py extension that contains functions and variables.
Another method is to write the modules in the native language in which the Python interpreter itself was written. For example, you can write modules in the C programming language and when compiled, they can be used from your Python code when using the standard Python interpreter.
A module can be imported by another program to make use of its functionality. This is how we can use the Python standard library as well. First, we will see how to use the standard library modules.
# module.py
import sys # This import the module.
print('The command line arguments are:')
for i in sys.argv:
print i
print '\n\nThe PYTHONPATH is', sys.path, '\n'
>> python module.py we are arguments
# -> The command line arguments are:
# -> module_using_sys.py
# -> we
# -> are
# -> arguments
>> # ['', '/usr/lib/python2.7', '/usr/lib/python2.7/plat-x86_64-linux-gnu', '/usr/lib/python2.7/lib-tk', '/usr/lib/python2.7/lib-old', '/usr/lib/python2.7/lib-dynload', '/home/ajepe/.local/lib/python2.7/site-packages', '/usr/local/lib/python2.7/dist-packages', '/usr/lib/python2.7/dist-packages', '/usr/lib/python2.7/dist-packages/gtk-2.0']First, we import the sys module using the import statement. Basically, this translates to us telling Python that we want to use this module. The sys module contains functionality related to the Python interpreter and its environment i.e. the system. When Python executes the import sys statement, it looks for the sys module. In this case, it is one of the built-in modules, and hence Python knows where to find it.
If it was not a compiled module i.e. a module written in Python, then the Python interpreter will search for it in the directories listed in its sys.path variable. If the module is found, then the statements in the body of that module are run and the module is made available for you to use. Note that the initialization is done only the first time that we import a module.
If we want to directly import the argv variable into our program (to avoid typing the sys. everytime for it), then we can use the
from sys import argvIn general, if possible we should try to avoid using this statement and use the import statement instead, by doing that our program will avoid name clashes and will be more readable.
##Creating our own modules Creating our own modules is a cinch, we have been doing it all along! This is because every Python program is also a module. We just have to make sure it has a .py extension. The following example should make it clear.
# my_module.py
def say_hello():
print 'Hello to the people of the work'
__version__ = '0.0.1'The code above is a sample module. As we can see, there is nothing particularly special about it compared to our usual Python program. We will next see how to use this module in our other Python programs.
Note that the module should be placed either in the same directory as the program from which we import it, or in one of the directories listed in sys.path.
# another_module.py
import my_module # importing our first module
# now, let us call say_hello function in my_module
my_module.say_hello() # - > 'Hello to the people of the work'
print __my_module.__version__ # -> 0.0.1
Note that we use the same dotted notation to access members of the module.
from my_module import say_hello, __version__
say_hello() # - > 'Hello to the people of the work'
print 'Version', __version__ # -> 0.0.1Just like functions, modules are reusable programs. Packages are another hierarchy to organize modules. The standard library that comes with Python is an example of such a set of packages and modules. We have seen how to use these modules and create our own modules.
In Python, there are four built-in data structures
- List
- Tuple
- Dictionary
- Set.
A list is a data structure that holds a collection of items and it's a mutable data type i.e. this type can be altered.
Example
# This is my shopping list
cart = ['shoe', 'bag', 'powder', 'belt']
print 'I have', len(cart), 'items to purchase.' # This will return total number of items in the cart.
print 'These items are:',
for item in cart:
print item, # we iterate through the total items to print each item in the cart
# Now let us add more items to the cart
cart.append('red shoe')
print cart # ['shoe', 'bag', 'powder', 'belt', 'red shoe']The variable cart is our shopping list, In shoplist , we only store strings of the names of the items to buy but we can add any kind of object to a list including numbers and even other lists. We also used the for..in loop to iterate through the items of the cart. To know all the methods defined by the list object, see help(list) for more details.
Tuples are used to hold together multiple objects. Tuple behave in a similar way to lists, but without the all the functionality that the list class gives us. One major feature of tuples is that they are immutable like strings i.e. we cannot modify tuples. Tuples are defined by specifying items separated by commas within an optional pair of parentheses.
zoo = ('python', 'elephant', 'penguin')
print 'Number of animals in the zoo is', len(zoo)The variable zoo refers to a tuple of items. We see that the len function can be used to get the length of the tuple. This also indicates that a tuple is a sequence as well. To know all the methods defined by the list object, see help(list) for more details.
A dictionary is like an address-book where you can find the address or contact details of a person by knowing only his/her name i.e. we associate keys (name) with values. The key must be unique and we can use only immutable objects (like strings) for the keys of a dictionary but we can use either immutable or mutable objects for the values of the dictionary. This basically translates to say that you should use only simple objects
d = {key1 : value1, key2 : value2 } . Notice that the key-value pairs are separated by a colon and the pairs are separated themselves by commas and all this is enclosed in a pair of curly braces. Remember that key-value pairs in a dictionary are not ordered in any manner (in python version < 3.7).
bio_data = {
'name' : 'John doe',
'Age' : 18,
'sex' : 'Male'.
'Status' : 'single
}
# let us print out the bio data information
for key, value in bio_data.items():
print '{} {}'.format(key, value)
# we can add more information
bio_data['email'] = 'johndoe@gmail.com'
# if we print the bio_data now, we should have
print bio_data # -> {'name' : 'John doe', 'Age' : 18, 'sex' : 'Male'. 'status' : 'single', 'email : 'johndoe@gmail.com'}Sets are unordered collections of simple objects. These are used when the existence of an object in a collection is more important than the order or how many times it occurs. Using sets, you can test for membership, whether it is a subset of another set, find the intersection between two sets, and so on.
country_in_africa = set(['Nigeria', 'Ghana', 'Togo', 'Liberia])
'Nigeria' in country_in_africa # -> True
'Gemany' in country_in_africa # -> FalseThe example is pretty much self-explanatory because it involves basic set theory mathematics taught in school, we can add, remove and also find the union, intersert of the set.
All through till now, we designed our program around functions. This is called the procedure-oriented way of programming. There is another better way of organizing our program/code which is to combine data and functionality and wrap it inside something called an object. This is called the object oriented programming paradigm. Most of the time we can use procedural programming, but when writing large or complex programs we can use object oriented programming techniques.
Classes and objects are the two main aspects of object oriented programming. A class creates a new type where objects are instances of the class. An analogy is that we can have variables of type int which translates to saying that variables that store integers are variables which are instances (objects) of the int class.
Objects can store data using ordinary variables that belong to the object. Variables that belong to an object or class are referred to as fields or property. Objects can also have functionality by using functions that belong to a class. Such functions are called methods of the class. This terminology is important because it helps us to differentiate between functions and variables which are independent and those which belong to a class or object. Collectively, the fields and methods can be referred to as the attributes of that class.
A class is created using the class keyword. The fields and methods of the class are listed in an indented block.
Class methods have only one specific difference from ordinary functions - they must have an extra first name that has to be added to the beginning of the parameter list, but you do not give a value for this parameter when you call the method, Python will provide it. This particular variable refers to the object itself, and by convention, it is given the name self.
# class definition
class Person(object):
"""Don't forget your docstring always."""
pass # An empty block
p = Person()
print(p) # - >>> <__main__.person object at 0x7f89445a2f50>We create a new Person class using the class statement, this is followed by an indented block of statements which form the body of the class. In this case, we have an empty block which is indicated using the pass statement.
Then, we instantiate the object using the name of the class followed by a pair of parentheses. We can verify, the type of the variable by simply printing it. It tells us that we have an instance of the Person class in the main module.
We have already discussed that classes/objects can have methods just like functions except that we have an extra self variable. Example
class Person:
"""docstring."""
def talk(self):
print('Hi, I can talk.')
def walk(self):
print('See, I can also walk.')
# instance of the lass Person
p = Person()
p.walk() # -> Hi, I can talk.
p.talk() # -> See, I can also walk
Here we see the self keyword in action. Notice that the walk and talk method takes no arguments, but still has the self in the function definition.
There are many method names which have special significance in Python classes. We will see how the init method is useful now.
The _init_ method is run as soon as an object of a class is instantiated. The method is useful to do any initialization you want to do with your object. Notice the double underscores both at the beginning and at the end of the name. Example
class Person:
"""docstring."""
def __init__(self, name):
self.name = name
def talk(self):
print('Hi {}, can talk.'.fortmat(self.name))
def walk(self):
print('See, {} can also walk.'.format(self.name))
# to instatiate class Person now requires the person's name
p = Person('Ajepe')
p.walk() -> # Hi Ajepe, I can talk.
p.talk() # -> See, Ajepe can also walkHere, we define the init method as taking a parameter name (along with the usual self ). Then, we created a new field/property called name, notice also that we do not explicitly call the init method but pass the arguments in the parentheses following the class name when creating a new instance of the class. Now, we are able to use the self.name field or property in our methods.
One of the major benefits of object oriented programming is reuseability of code and one of the ways this is achieved is through the inheritance mechanism. Inheritance can be best imagined as implementing a parent and child relationship between classes.
Suppose you want to write a program which has to keep track of the teachers and students in a college. They have some common characteristics such as name, age and address. They also have specific characteristics such as salary, courses and leaves for teachers and, marks and fees for students. We can create two independent classes for each type and process them but adding a new common characteristic would mean adding to both of these independent classes.
A better way would be to create a common class called Member and then have the teacher and student classes inherit from this class(Member) i.e. they will become sub-types or child of Member class, and then we can add specific characteristics to these sub-types(child classes). There are many advantages to this approach.
class Member:
"""Represents any school member."""
def __init__(self, name, age):
self.name = name
self.age = age
print '(Initialized SchoolMember: {})'.format(self.name)
def tell(self):
"""Tell my details."""
print 'Name:"{}" Age:"{}"'.format(self.name, self.age),
class Teacher(Member):
"""Represents a teacher."""
def __init__(self, name, age, salary):
Member.__init__(self, name, age)
#super(Member, self)__init__(self, name, age) This is the standard way of doing it.
self.salary = salary
print '(Initialized Teacher: {})'.format(self.name)
def tell(self):
Member.tell(self)
print 'Salary: "{:d}"'.format(self.salary)
class Student(Member):
"""Represents a student."""
def __init__(self, name, age, marks):
Member.__init__(self, name, age)
#super(Student, self)__init__(self, name, age) This is the standard way of doing it.
self.marks = marks
print '(Initialized Student: {})'.format(self.name)
def tell(self):
Member.tell(self)
print 'Marks: "{:d}"'.format(self.marks)
# -> teacher = Teacher('John Doe', 50, 30000)
# -> s = Student('Jane JIn', 25, 75)We can use inheritance in python by specifying the base class names in a tuple following the class name in the class definition. Next, we observe that the init method of the base class is explicitly called using the self variable so that we can initialize the base class part of the object. This is very important to remember - Python does not automatically call the constructor of the base class,we have to explicitly call it ourself.
Note that we can treat instances of Teacher or Student as just instances of the Member when we use the tell method of the Member class.
We have now explored the various aspects of classes and objects as well as the various terminologies associated with it. We have also seen the benefits of object-oriented programming. Python is highly object oriented and understanding these concepts carefully will help us a lot. files in Python.