function, module and class · in python, “__main__” is the name of the scope where top-level...
TRANSCRIPT
DATA STRUCTURE AND
ALGORITHM USING PYTHON
Peter Lo
Function, Module and Class
Develop Reusability Resource
Function
2Data Structure and Algorithm using Python @ Peter Lo 2019
What is Function?
3
A function is a sequence of statements in a certain
order, given a name.
When called, those statements are executed.
We don’t have to write the code again and again for
each type of data that we want to apply it to.
This is called code re-usability.
Data Structure and Algorithm using Python @ Peter Lo 2019
Type of Python Functions
4Data Structure and Algorithm using Python @ Peter Lo 2019
User-defined Functions
5
Python lets us group a sequence of statements into a
single entity, called a function.
A Python function may or may not have a name.
Data Structure and Algorithm using Python @ Peter Lo 2019
Advantages of Functions
6
Functions help divide a program into modules.
This makes the code easier to manage, debug, and
scale.
It implements code reuse.
Every time you need to execute a sequence of
statements, all you need to do is to call the function.
Functions allow us to change functionality easily, and
different programmers can work on different functions.
Data Structure and Algorithm using Python @ Peter Lo 2019
Creating User-defined Functions
7
Python uses def keyword to start a function.
All statements inside the function should be indented
using equal spaces
Data Structure and Algorithm using Python @ Peter Lo 2019
Calling Function
8
To apply the function, we must call it. We must ask the
function to do its job.
We will obtain its result once we type its name and
parentheses.
Data Structure and Algorithm using Python @ Peter Lo 2019
Creating Function with Parameter
9
Function can accept zero or more arguments (also
known as parameters) enclosed in parentheses.
Data Structure and Algorithm using Python @ Peter Lo 2019
Return Value from Function
10
By using return statement, functions that return values
can be used in expressions.
When an expression with a function call is evaluated,
the function call is effectively replaced temporarily by its
returned value.
Data Structure and Algorithm using Python @ Peter Lo 2019
Return without Value (None)
11
You can use the return statement without a return value.
If there is no value assigned in return statement, “None”
will be returned.
Data Structure and Algorithm using Python @ Peter Lo 2019
Returning Multiple Values
12
We can return multiple values from function using the
return statement by separating them with a comma.
Multiple values are returned as tuples
Data Structure and Algorithm using Python @ Peter Lo 2019
Passing Parameters to Function
13
You can call a function by using the following types of
formal arguments:
Required Arguments
Keyword Arguments
Default Arguments
Variable-Length Arguments
Data Structure and Algorithm using Python @ Peter Lo 2019
Calling Function by Required Arguments
14
Required arguments are the arguments passed to a
function in correct positional order.
i.e. the number of arguments in the function call
should match exactly with the function definition.
Data Structure and Algorithm using Python @ Peter Lo 2019
Data Structure and Algorithm using Python @ Peter Lo 2019
Calling Function by Keyword Arguments
15
When you use keyword arguments in a function call, the
caller identifies the arguments by the parameter name.
This allows you to pass each arguments using name
value pairs like “name=value”.
This allows you to skip arguments or place them out of
order because the Python interpreter is able to use the
keywords provided to match the values with parameters.
Calling Function by Default Arguments
A default argument is an argument that assumes a
default value if a value is not provided in the function call
for that argument.
Python supports named parameters, so that when a
function is called, parameters can be explicitly assigned
a value by name. These are often used to implement
default, or optional, values.
Data Structure and Algorithm using Python @ Peter Lo 2019 16
Calling Function by Variable-Length Arguments
17
You may need to process a function for more arguments than you
specified while defining the function.
These arguments are called variable-length arguments and are not
named in the function definition, unlike required and default
arguments.
An asterisk (*) is placed before the variable name that holds the
values of all non keyword variable arguments.
Data Structure and Algorithm using Python @ Peter Lo 2019
Built-in Functions
18
The Python interpreter has a number of functions that are always
available for use. These functions are called built-in functions.
For example, print() function prints the given object to the
standard output device (screen) or to the text stream file.
Data Structure and Algorithm using Python @ Peter Lo 2019
Lambda Expressions (Anonymous Functions)
19
A function doesn’t need to have a name. A lambda
expression allows us to create anonymous python
functions, and we use the ‘lambda’ keyword for it.
It’s worth noting that it can have any number of
arguments, but only one expression. It evaluates the
value of that expression, and returns the result
Data Structure and Algorithm using Python @ Peter Lo 2019
lambda [arg1 [,arg2,.....argn]]:expression
Lambda Example
20
Simple Lambda function example:
The above Lambda function is the same as the below
function.
Data Structure and Algorithm using Python @ Peter Lo 2019
More about Anonymous Functions
21
These functions are called anonymous because they are not declared in the standard manner by using the def keyword.
Lambda forms can take any number of arguments but return just one value in the form of an expression. They cannot contain commands or multiple expressions.
An anonymous function cannot be a direct call to print because lambda requires an expression
Lambda functions have their own local namespace and cannot access variables other than those in their parameter list and those in the global namespace.
Although it appears that lambda's are a one-line version of a function, they are not equivalent to inline statements in C or C++, whose purpose is by passing function stack allocation during invocation for performance reasons.
Data Structure and Algorithm using Python @ Peter Lo 2019
Recursive Function
22
A recursive function is a function defined in terms of
itself via self-referential expressions.
This means that the function will continue to call itself
and repeat its behavior until some condition is met to
return a result.
All recursive functions share a common structure made
up of two parts:
Base Case
Recursive Case
Data Structure and Algorithm using Python @ Peter Lo 2019
Example
23
To demonstrate the recursive function for calculating n!:
Decompose the original problem into simpler instances of the
same problem. This is the recursive case:
As the large problem is broken down into successively less
complex ones, those sub problems must eventually become so
simple that they can be solved without further subdivision. This is
the base case
Data Structure and Algorithm using Python @ Peter Lo 2019
Example (Cont.)
24
Recursive function for calculating n! in Python is:
Data Structure and Algorithm using Python @ Peter Lo 2019
Example (Cont.)
25
each recursive call adds a stack frame to the call stack
until we reach the base case. Then, the stack begins to
unwind as each call returns its results:
Data Structure and Algorithm using Python @ Peter Lo 2019
Main Program
26
In Python, “__main__” is the name of the scope where top-level code will execute. There is a convention to use the following construction:
This lets program files be used either:
As the main program and run what follows the if statement
As a module and not run what follows the if statement.
Any code that is not contained within this statement will be executed upon running.
Data Structure and Algorithm using Python @ Peter Lo 2019
Local and Global Variables Overview
Variable Scope and Lifetime
27Data Structure and Algorithm using Python @ Peter Lo 2019
What is a Name?
28
Name (also called identifier) is simply a name given to
objects. Everything in Python is an object. Name is a
way to access the underlying object.
When we define a variable we are giving it a name
and that variable is assigning a object which is holding
the value.
Data Structure and Algorithm using Python @ Peter Lo 2019
Namespace
29
Names live in namespaces (such as a module namespace, an
instance namespace, a function’s local namespace).
Namespaces are collections of (name, object reference) pairs
(implemented using dictionaries).
When you call a function or a method, its namespace is initialized
with the arguments you call it with (the names are taken from the
function’s argument list, the objects are those you pass in).
Data Structure and Algorithm using Python @ Peter Lo 2019
Namespaces are created by packages, modules,
classes, object construction and functions. There
aren’t any other flavors of namespaces
Variable Scope and Lifetime
30
Not all variables are accessible from all parts in
program, and not all variables exist for the same amount
of time.
The Scope of a variable refers to that part of a
program that may refer to the variable.
The Lifetime of a variable refers to the time in which
a variable occupies a place in memory
The scope and lifetime of a variable are determined by
how and where the variable is defined.
Data Structure and Algorithm using Python @ Peter Lo 2019
Local Variable
31
A variable which is defined inside a function or loop is local is called Local Variable.
It is accessible from the point at which it is defined until the end of the function, and exists for as long as the function is executing.
The parameter names in the function definition behave like local variables, but they contain the values that we pass into the function when we call it.
When we use the assignment operator (=) inside a function, its default behavior is to create a new local variable – unless a variable with the same name is already defined in the local scope.
Data Structure and Algorithm using Python @ Peter Lo 2019
Global Variables
32
A variable which is defined in the main body of a file is
called a Global Variable.
It will be visible throughout the file, and also inside any
file which imports that file.
Global variables can have unintended consequences
because of their wide-ranging effects – that is why we
should almost never use them.
Only objects which are intended to be used globally, like
functions and classes, should be put in the global
namespace.
Data Structure and Algorithm using Python @ Peter Lo 2019
LEGB Rules
33
When a variable is referenced, Python search for it in this order: in
the local scope, in any enclosing function's local scope, in the global
scope and finally in the built-in scope. The first occurrence wins.
Data Structure and Algorithm using Python @ Peter Lo 2019
Declare Global Variables
34
In Python, global variable can be accessed inside or
outside of the function.
Data Structure and Algorithm using Python @ Peter Lo 2019
We created a global variable and defined a function to
print the global variable. Finally, we call the function
which will print the value out.
Incorrect using Global Variables
35Data Structure and Algorithm using Python @ Peter Lo 2019
The output shows an error because
Python treats variable as a local variable
and it is not defined inside function
Local variable can use same name with global variable
Local vs. Global Variable
36Data Structure and Algorithm using Python @ Peter Lo 2019
Local variable
within functionGlobal variable
Global Keyword
37
Local variable can be bind in global scope by using the
global keyword followed by the names of variables.
With global, you're telling Python to use the globally
defined variable instead of locally defining it.
Data Structure and Algorithm using Python @ Peter Lo 2019
The nonlocal Keyword
38Data Structure and Algorithm using Python @ Peter Lo 2019
Scope of life
The nonlocal statement is useful in nested functions. It causes the
variable to refer to the previously bound variable in the closest
enclosing scope. In other words, it will prevent the variable from
trying to bind locally first, and force it to go a level 'higher up'.
The nonlocal Keyword (Cont.)
39
The lifetime for variable without key nonlocal is inside
nested functions only.
Data Structure and Algorithm using Python @ Peter Lo 2019
Scope of life
Scope of Life
40
Scope for life for local variable is inside function only
Data Structure and Algorithm using Python @ Peter Lo 2019
Scope of life
Group of Functions
Modules
41Data Structure and Algorithm using Python @ Peter Lo 2019
What is Module?
42
A module is a file containing Python definitions and
statements.
The file name is the module name with the suffix .py
appended.
Within a module, the module’s name (as a string) is
available as the value of the global variable __name__.
Data Structure and Algorithm using Python @ Peter Lo 2019
Create Custom Module
43
Modules are quite easy to create. They are simply Python files, like
your regular scripts.
To create a module, write one or more functions in a text file, then
save it with a .py extension.
To use the module, just import the filename, and call the function
Data Structure and Algorithm using Python @ Peter Lo 2019
Built-in Modules
44
There are plenty of built in modules, just as there are
with built in functions. This is where Python really excels!
It takes what’s called the “batteries included” approach.
Some common use module:
random
math
os
datetime
Data Structure and Algorithm using Python @ Peter Lo 2019
Module random
45
This module lets you generate random numbers.
For example, when using Python to create a website,
they can be used in making your password database
more secure or powering a random page feature.
Data Structure and Algorithm using Python @ Peter Lo 2019
Module math
46
The math module provides access to mathematical
constants and functions
Data Structure and Algorithm using Python @ Peter Lo 2019
Module os
47Data Structure and Algorithm using Python @ Peter Lo 2019
Module os provides functions that interface with the
underlying operating system
E.g. path submodule allows you to manipulate and
find the properties of files and folders on the system
Module datetime
48Data Structure and Algorithm using Python @ Peter Lo 2019
If you need to work with dates and times, then the
datetime module is your friend.
You can also import the date and the time components
separately, so you don't have to type as much later
The strftime reference can be obtained from
http://strftime.org
Object, Class and Instance
Object Oriented Programming
49Data Structure and Algorithm using Python @ Peter Lo 2019
Object
50
Real-world objects share two characteristics: They all
have state and behavior.
E.g. Dogs have state (name, color, breed, hungry)
and behavior (barking, fetching, wagging tail).
Identifying the state and behavior for real-world objects
is a great way to begin thinking in terms of object-
oriented programming.
Data Structure and Algorithm using Python @ Peter Lo 2019
Software Object
51
Software objects are conceptually similar to real-world
objects, they also consist of state and related behavior.
An object stores its state in fields (variables in some
programming languages) and exposes its behavior
through methods (functions in some programming
languages).
Data Structure and Algorithm using Python @ Peter Lo 2019
Object-Oriented Programming
52
Object-oriented Programming (OOP) is a programming
paradigm which provides a means of structuring
programs so that properties and behaviors are bundled
into individual objects.
Object-oriented programming models real-world entities
as software objects, which have some data associated
with them and can perform certain functions.
The key takeaway is that objects are at the center of the
object-oriented programming paradigm, not only
representing the data, as in procedural programming,
but in the overall structure of the program as well.
Data Structure and Algorithm using Python @ Peter Lo 2019
Class
53
A class is a blueprint or template or set of instructions to
build a specific type of object.
Basically, a class will consists of field, static field,
method, static method and constructor.
Field is used to hold the state of the class (eg: name
of Student object).
Method is used to represent the behavior of the class
(eg: how a Student object going to stand-up).
Constructor is used to create a new Instance of the
Class.
Data Structure and Algorithm using Python @ Peter Lo 2019
Instance
54
An instance is a specific object built from a specific class.
It is assigned to a reference variable that is used to
access all of the instance's properties and methods.
For instance, it is a unique copy of a Class that
representing an Object.
When a new instance of a class is created, a room of
memory is allocated for that class instance.
Data Structure and Algorithm using Python @ Peter Lo 2019
Objects and Classes
55
Languages that support object-oriented programming
typically use inheritance for code reuse and extensibility
in the form of either classes or prototypes.
Those that use classes support two main concepts:
Classes – the definitions for the data format and
available procedures for a given type or class of
object
Objects – instances of classes
Data Structure and Algorithm using Python @ Peter Lo 2019
Defining a Class
56
To define a class, in typical simple Python fashion, we
use the word class, followed by the name of your new
class.
We use a colon after the name, and then anything
contained within the class definition is indented.
There is no parentheses with a class
Data Structure and Algorithm using Python @ Peter Lo 2019
Define a Property for Class (Indentation)
57
In order to give the class a couple of properties, simply
define some variables inside the class.
A value also need to defined for each variable.
Data Structure and Algorithm using Python @ Peter Lo 2019
it doesn’t matter in this case since the number of legs will
be specific to each instance of the class - a fish doesn’t
have the same amount of legs as a dog or a duck, etc.
The value need to change for each object anyway
Create an Instance (Object) for Class
58
A class on its own isn’t something you can directly manipulate; first,
we have to create an instance of the class to play with. We can
store that instance in a variable.
Outside of the class (without any indentation), let’s make an
instance of the class and store it in the variable.
To make a new instance of a class, you simply type the name of the
class, and then a pair of parentheses.
The parentheses is a way of passing in a variable for use by the
class when you first create the instance.
Data Structure and Algorithm using Python @ Peter Lo 2019
A class on its own isn’t something that
you can directly manipulate.
Access to Property of Object
59
To reference a property of an object, first we have to tell
Python which object (or which instance of a class) we’re
talking about. Then we’re going to write a period to
indicate that we’re referencing something that’s
contained within our instance. After the period, we add
the name of our variable.
Data Structure and Algorithm using Python @ Peter Lo 2019
Create Method
60
Methods are functions contained within a class.
You define one in exactly the same way as you would a function,
but the difference is that you put it inside a class, and it belongs to
that class.
If you ever want to call that method, you have to reference an object
of that class first, just like the variables.
Data Structure and Algorithm using Python @ Peter Lo 2019
Create Method with Data
61
When we were accessing variables from outside the class, we have
to reference it by first specifying the instance containing that
variable.
'self' is just a reference to the object that is currently being
manipulated. So to access a variable in the current class, you
simply need to preface it with 'self' and then a period
Data Structure and Algorithm using Python @ Peter Lo 2019
Instance Attributes
62
All classes create objects, and all objects contain
characteristics called attributes (referred to as properties
in the opening paragraph).
Use the __init__() method to initialize (e.g., specify) an
object’s initial attributes by giving them their default
value (or state).
This method must have at least one argument as well as
the self variable, which refers to the object itself.
Data Structure and Algorithm using Python @ Peter Lo 2019
Class Attributes
63
While instance attributes are specific to each object,
class attributes are the same for all instances.
Data Structure and Algorithm using Python @ Peter Lo 2019
Instantiating Objects
64
Instantiating is a fancy term for creating a new, unique
instance of a class.
Data Structure and Algorithm using Python @ Peter Lo 2019
Instance Methods
65Data Structure and Algorithm using Python @ Peter Lo 2019
Instance methods are defined inside a class and are used to get the
contents of an instance.
They can also be used to perform operations with the attributes of our
objects. Like the __init__ method, the first argument is always self:
Child Class
66Data Structure and Algorithm using Python @ Peter Lo 2019
Inheritance is the process by which one class takes on
the attributes and methods of another. Newly formed
classes are called Child Classes, and the classes that
child classes are derived from are called Parent Classes.
Child classes inherit all of the parent’s attributes and
behaviors but can also specify different behavior to
follow.
The most basic type of class is an object, which
generally all other classes inherit as their parent
Example
67Data Structure and Algorithm using Python @ Peter Lo 2019
List of Common Built-In Functions
Built-in Function
68Data Structure and Algorithm using Python @ Peter Lo 2019
Built-in Functions
69
Python provides a number of built-in functions for
manipulating number and string.
These functions can be used on any data type.
There are a number of modules available in the Python
Standard Library as well, such as math. To use the
functions associated with these modules, you’ll first have
to import the module.
Data Structure and Algorithm using Python @ Peter Lo 2019
Math
70Data Structure and Algorithm using Python @ Peter Lo 2019
Type Conversion
71Data Structure and Algorithm using Python @ Peter Lo 2019
Iterators
72Data Structure and Algorithm using Python @ Peter Lo 2019
Composite Data Type
73Data Structure and Algorithm using Python @ Peter Lo 2019
Classes, Attributes, and Inheritance
74Data Structure and Algorithm using Python @ Peter Lo 2019
Input / Output
75Data Structure and Algorithm using Python @ Peter Lo 2019
Variables, References, and Scope
76Data Structure and Algorithm using Python @ Peter Lo 2019
Miscellaneous
77Data Structure and Algorithm using Python @ Peter Lo 2019