SlideShare une entreprise Scribd logo
1  sur  151
Télécharger pour lire hors ligne
TRAINING PYTHON
INTRODUCTION TO PYTHON
(BASIC LEVEL)
Editor: Nguyễn Đức Minh Khôi
@HCMC University of Technology, September 2011
9/2/2011

Training Python Chapte 0: Introduction to Python

TRAINING PYTHON
Chapter 0: INTRODUCTION TO PYTHON

1
9/2/2011

Training Python Chapte 0: Introduction to Python

2

CONTENTS
Python in general
How Python program runs?
How to run Python?
9/2/2011

Training Python Chapte 0: Introduction to Python

3

Python in general
• What is python?
• High level programming language
• Emphasize on code readability
• Very clear syntax + large and comprehensive standard library
• Use of indentation for block delimiters
• Multiprogramming paradigm: OO, imperative, functional,
procedural, reflective
• A fully dynamic type system and automatic memory management
• Scripting language + standalone executable program + interpreter
• Can run on many platform: Windows, Linux, Mactonish

• Updates:
• Newest version: 3.2.2 (CPython, JPython, IronPython)
• Website: www.python.org
9/2/2011

Training Python Chapte 0: Introduction to Python

4

Python in general (Cont’)
• Advantages:
• Software quality
• Developer productivity
• Program portability
• Support libraries
• Component integration
• Enjoyment
• Disadvantages:
• not always be as fast as that of compiled languages such as C and
C++
9/2/2011

Training Python Chapte 0: Introduction to Python

Python in general (Cont’)
• Applications of python:

5
9/2/2011

Training Python Chapte 0: Introduction to Python

Python in general (Cont’)
• Python’s Capability:
• System Programming
• GUI
• Internet Scripting
• Component Integration
• Database Programming
• Rapid Prototyping
• Numeric and Scientific Programming
• Gaming, Images, Serial Ports, XML, Robots, and More

6
9/2/2011

Training Python Chapte 0: Introduction to Python

7

How Python program runs?

Notice: pure Python code runs at speeds somewhere between those of
a traditional compiled language and a traditional interpreted language
9/2/2011

Training Python Chapte 0: Introduction to Python

How to run Python?
• Install Python 3.2.2:
• Go to website:
http://www.python.org/download/ and
download the latest version of Python
• Run and install follow the instructions
of the .msi file
• If you successfully install, you will see
this picture:
• Coding Python:
• Not IDE support: use notepad++
http://notepad-plus-plus.org/
• Use IDE support: Eclipse (3.7) or
Netbeans (7.0)

8
9/2/2011

Training Python Chapte 0: Introduction to Python

9

How to run Python? (Cont’)
• Install Eclipse: follow the instructions from this website:
http://wiki.eclipse.org/FAQ_Where_do_I_get_and_install_Eclipse%3F
(you should download the Eclipse Classics version)
• Install Pydev plugin for eclipse: follow this instruction:
http://pydev.org/manual_101_install.html
9/2/2011

Training Python Chapte 0: Introduction to Python

10

THANKS FOR LISTENING
Editor: Nguyễn Đức Minh Khôi
Contact: nguyenducminhkhoi@gmail.com
Main reference: Part I – Getting Started
Learning Python – O’reilly
TRAINING PYTHON
CHAPTER 1: TYPES AND OPERATIONS
CONTENTS
Lists
Dictionaries
Tuples
Files
Numeric Typing
Dynamic Typing
Summary
5/22/2011

Training Python

3

Lists
• Ordered collections of arbitrary objects
• Accessed by offset
• Variable-length, heterogeneous, and arbitrarily nestable

• Of the category “mutable sequence”
• Arrays of object references
5/22/2011

Training Python

Lists literals and operations

4
5/22/2011

Training Python

5

Lists literals and operations (cont’)
5/22/2011

Training Python

6

Dictionaries
• Accessed by key, not offset
• Accessed by key, not offset
• Variable-length, heterogeneous, and arbitrarily nestable

• Of the category “mutable mapping”
• Tables of object references (hash tables)
5/22/2011

Training Python

7

Dictionaries literals and operations
5/22/2011

Training Python

8

Dictionaries literals and operations (c)
5/22/2011

Training Python

9

Tuples
• Ordered collections of arbitrary objects
• Accessed by offset
• Of the category “immutable sequence”

• Fixed-length, heterogeneous, and arbitrarily nestable
• Arrays of object references
5/22/2011

Training Python

Tuples literals and operations

10
5/22/2011

Training Python

11

Tuples literals and operations (con’t)
5/22/2011

Training Python

Files – common operations

12
2

NUMERIC TYPES
• Integers and floating-point numbers
• Complex numbers
• Fixed-precision decimal numbers
• Rational fraction numbers
• Sets

• Booleans
• Unlimited integer precision
• A variety of numeric built-ins and modules
3

NUMERIC TYPES (Cont’)
4

NUMERIC TYPES (Cont’)
Dynamic Typing
• Variables, Objects, References:
• Variables are entries in a system table, with spaces for links to
objects.
• Objects are pieces of allocated memory, with enough space to
represent the values for which they stand.
• References are automatically followed pointers from variables to
objects.
Dynamic Typing (Cont’) - Shared references
• Immutable types:
Dynamic Typing (Cont’) - Shared references
• Mutable types:

• Notices:
• It’s also just the default: if you don’t want such behavior, you can

request that Python copy objects instead of making references.
Dynamic Typing (Cont’) - Shared references
• Notices (next):
• “is” function returns False if the names point to equivalent but different
objects, as is the case when we run two different literal expressions.
• Small integers and strings are cached and reused, though, is tells us
they reference the same single object.
5/22/2011

Summary
• Object just classification

Training Python

13
5/22/2011

Training Python

14

Summary (con’t)
• Object Flexibility
• Lists, dictionaries, and tuples can hold any kind of object.
• Lists, dictionaries, and tuples can be arbitrarily nested.
• Lists and dictionaries can dynamically grow and shrink.
• Object copy
• Slice expressions with empty limits (L[:]) copy sequences.
• The dictionary and set copy method (X.copy()) copies a dictionary
or set.
• Some built-in functions, such as list, make copies (list(L)).
• The copy standard library module makes full copies.
9/2/2011

Learning Python Chapter 1

1

THANKS FOR LISTENING
Editor: Nguy n Đ c Minh Khôi
Contact: nguyenducminhkhoi@gmail.com
Main reference: Part II – Types and Operations
Learning Python – O’reilly
9/2/2011

Learning Python Chapter 2

TRAINING PYTHON
STATEMENTS AND SYNTAX

1
9/2/2011

Learning Python Chapter 2

Content
Statements
Assignment, Expression, Print
Conditional statements
Loop statements
Iterations and comprehensions

2
9/2/2011

Learning Python Chapter 2

Python program structures:
• Programs are composed of modules.
• Modules contain statements.
• Statements contain expressions.
• Expressions create and process objects.

3
9/2/2011

Learning Python Chapter 2

Python statements

4
9/2/2011

Learning Python Chapter 2

Python statements (Cont’)

5
9/2/2011

Learning Python Chapter 2

Python statements (Cont’)

6
9/2/2011

Learning Python Chapter 2

Assignment Statements
Assignment Properties:
• Assignments create object references
• Names are created when first assigned
• Names must be assigned before being referenced
• Some operations perform assignments implicitly

Assignment Statement Forms:

7
9/2/2011

Learning Python Chapter 2

8

Variable name rules (opt)
• Syntax: (underscore or letter) + (any number of letters,

digits, or underscores)
• Case matters: SPAM is not the same as spam
• Reserved words are off-limits
9/2/2011

Learning Python Chapter 2

Expression Statements

9
9/2/2011

Print Operations
• Call format

• Example:

Learning Python Chapter 2

10
9/2/2011

Learning Python Chapter 2

Conditional Statements - IF
• General Format:

• The if/else ternary expression:
• Example:

11
9/2/2011

Learning Python Chapter 2

12

IF Statements - Truth tests (opt)
Conditional expression:
• Any nonzero number or nonempty object is true.
• Zero numbers, empty objects, and the special object None are

considered false.
• Comparisons and equality tests are applied recursively to data
structures.
• Comparisons and equality tests return True or False (custom versions
of 1 and 0).
• Boolean “and” and “or” operators return a true or false operand
object.
9/2/2011

Learning Python Chapter 2

13

IF Statements - Truth tests (opt) (Cont)
• “and” and “or” operands:
9/2/2011

Learning Python Chapter 2

14

Loop Statements – while statements
• General while format:

• Notice:
9/2/2011

Learning Python Chapter 2

15

Loop Statements – for statements
• General Format:

• Loop Coding Techniques:
• The built-in range function produces a series of successively higher
integers, which can be used as indexes in a for.
• The built-in zip function returns a series of parallel-item tuples,
which can be used to traverse multiple sequences in a for.

• Notice: for loops typically run quicker than while-based counter
loops, it’s to your advantage to use tools like these that allow you to
use for when possible.
9/2/2011

Learning Python Chapter 2

Loop statements - examples

16
9/2/2011

Learning Python Chapter 2

17

Iterations and comprehensions
• Iterable:
• an object is considered iterable if it is either a physically stored
sequence or an object that produces one result at a time in the
context of an iteration tool like a for loop.
• iterable objects include both physical sequences and virtual
sequences computed on demand.

• Iterations:
• Any object with a __next__ method to advance to a next result,
which raises StopIteration at the end of the series of results, is
considered iterable in Python.
• Example:
9/2/2011

Learning Python Chapter 2

List comprehension
• Example:
• (x + 10): arbitrary expression
• (for x in L): iterable object
• Extend List Comprehension:

18
9/2/2011

Learning Python Chapter 2

19

New Iterator in Python 3.0
• Iterators associated:
• built-in type :set, list, dictionary, tuple, file
• Dictionary method: keys, values, items
• Built-in function: range (multiple iterator), map, zip, filter (single)
• Examples:
9/2/2011

Learning Python Chapter 2

Iterators examples (cont’)

20
9/2/2011

Learning Python Chapter 2

21

THANKS FOR LISTENING
Editor: Nguyễn Đức Minh Khôi
Contact: nguyenducminhkhoi@gmail.com
Main reference: Part III – Statements and Syntax
Learning Python – O’reilly
9/6/2011

Training Python Chapter 3

TRAINING PYTHON
Chapter 3: FUNCTION

1
9/6/2011

Training Python Chapter 3

2

CONTENTS
Function Basics

Scope
Arguments
Function Advanced
Iterations and Comprehension Advanced
9/6/2011

Training Python Chapter 3

Function Basics
• Function: A function is a device that groups a set of

statements so they can be run more than once in a
program.
• Why use?:
• Maximizing code reuse and minimizing redundancy
• Procedural decomposition

3
9/6/2011

Training Python Chapter 3

4

Function Basics – def Statements
• General format:

• Use “def” statements:
9/6/2011

Training Python Chapter 3

Function Basics – Examples

5
9/6/2011

Training Python Chapter 3

6

Scopes
• Three different scopes
• If a variable is assigned inside a def, it is local to that function.
• If a variable is assigned in an enclosing def, it is nonlocal to nested
functions.
• If a variable is assigned outside all defs, it is global to the entire file.
• Notice:
• All names assigned inside a function def statement (or a lambda,
an expression we’ll meet later) are locals by default.
• Functions can freely use names as-signed in syntactically
enclosing functions and the global scope, but they must declare
such nonlocals and globals in order to change them.
9/6/2011

Training Python Chapter 3

Scopes – the LEGB rules

7
9/6/2011

Training Python Chapter 3

8

Scopes – examples
Global names: X, func
Local names: Y, Z

# The Built – in Scopes
9/6/2011

Training Python Chapter 3

Scopes – Global statements
• Global Statement:

• Other ways to access Globals:

9
9/6/2011

Training Python Chapter 3

10

Scopes – Global statements(Cont’)
9/6/2011

Training Python Chapter 3

11

Scopes – Nested functions

• Factory function
• These terms refer to a function object that remembers values in enclosing

scopes regardless of whether those scopes are still present in memory.
9/6/2011

Training Python Chapter 3

Scopes – Nested scope (Cont’)
• Nested scope and lambda:

12
9/6/2011

Training Python Chapter 3

13

Scopes – Nonlocal statements
• The nonlocal statement:
• Is a close cousin to global
• Like global: nonlocal declares that a name will be changed in an
enclosing scope.
• Unlike global:
• nonlocal applies to a name in an enclosing function’s scope, not the

global module scope outside all defs.
• nonlocal names must already exist in the enclosing function’s scope
when declared

• Format:
9/6/2011

Training Python Chapter 3

14

Scopes – Nonlocal statements (Con’t)
9/6/2011

Training Python Chapter 3

15

Arguments – Passing Basics
• Arguments are passed by automatically assigning objects to local

•
•
•
•

variable names.
Assigning to argument names inside a function does not affect the
caller.
Changing a mutable object argument in a function may impact the
caller.
Immutable arguments are effectively passed “by value.”
Mutable arguments are effectively passed “by pointer.”
9/6/2011

Training Python Chapter 3

16

Arguments – Matching Modes

• Keyword-only arguments: arguments that must be passed by keyword

only and will never be filled in by a positional argument.
9/6/2011

Training Python Chapter 3

Arguments - Examples

17
9/6/2011

Training Python Chapter 3

Arguments – Examples (Cont’)

18
9/6/2011

Training Python Chapter 3

Arguments – Bonus Points

19
9/6/2011

Training Python Chapter 3

20

Function Advanced
• General guidelines:
• Coupling: use arguments for inputs and return for outputs.
• Coupling: use global variables only when truly necessary.
• Coupling: don’t change mutable arguments unless the caller
expects it.
• Cohesion: each function should have a single, unified purpose.
• Size: each function should be relatively small.
• Coupling: avoid changing variables in another module file directly.
9/6/2011

Training Python Chapter 3

Function Advanced - Recursions
• Examples:

• Alternatives:

21
9/6/2011

Training Python Chapter 3

22

Function Advanced – Lambda Expression
• Lambda format:
• Use lambda for:
• inline a function definition
• defer execution of a piece of code

• Notices:
• lambda is an expression, not a statement
• lambda’s body is a single expression, not a block of statements.
• If you have larger logic to code, use def; lambda is for small pieces of

inline code. On the other hand, you may find these techniques useful in
moderation

• Examples:
9/6/2011

Training Python Chapter 3

Lambda Expression (Cont’)
• Logic within lambda function:

• Nested lambda:

• Used with map function:
• Used with filter function:
• Used with reduce function:

23
9/6/2011

Training Python Chapter 3

24

Iterations and Comprehension Part 2
• List Comprehension:
• Vs. Map:

• Vs. filter:

• Vs. Nested for:
9/6/2011

Training Python Chapter 3

25

Iterations and Comprehension Part 2
• Generators:
• Generator functions: are coded as normal def statements but use
yield statements to return results one at a time, suspending and
resuming their state between each.
• Generator expressions: are similar to the list comprehensions
of the prior section, but they return an object that produces results
on demand instead of building a result list.
• Generator functions:
9/6/2011

Training Python Chapter 3

26

Iterations and Comprehension Part 2
• Generator Expression:
9/6/2011

Training Python Chapter 3

3.0 Comprehension Syntax

27
9/6/2011

Training Python Chapter 3

28

Function Pitfall
• “List comprehensions were nearly twice as fast as equivalent for

loop statements, and map was slightly quicker than list
comprehensions when mapping a built-in function such as abs
(absolute value)”
• Python detects locals statically, when it compiles the def’s code,
rather than by noticing assignments as they happen at runtime.
9/6/2011

Learning Python Chapter 2

29

THANKS FOR LISTENING
Editor: Nguyễn Đức Minh Khôi
Contact: nguyenducminhkhoi@gmail.com
Main reference: Part IV – Functions
Learning Python 4th Edition – O’reilly 2010
TRAINING PYTHON
Chapter 4: MODULES
9/15/2011

Training Python Chapter 4

Contents

Modules Basics
Modules Package
Modules in advance

2
9/15/2011

Training Python Chapter 4

3

Modules Basics
• Modules are process with:
• import: Lets a client (importer) fetch a module as a whole
• from: Allows clients to fetch particular names from a module
• imp.reload: Provides a way to reload a module’s code without
stopping Python
• Why use Modules?
• Code reuse
• System namespace partitioning
• Implementing service or data
9/15/2011

Training Python Chapter 4

4

Modules Basics – import statements
• How imports work?
1. Find the module’s file.
2. Compile it to byte code (if needed).
3. Run the module’s code to build the objects it defines.
• The Module Search Path:
1. The home directory of the program
2. PYTHONPATH directories (if set)
3. Standard library directories
4. The contents of any .pth files (if present)
9/15/2011

Training Python Chapter 4

5

Modules Basics – create Modules
• In fact, both the names of module files and the names of

directories used in package must conform to the rules for
variable names:
• They may, for instance, contain only letters, digits, and

underscores.
• Package directories also cannot contain platform-specific syntax
such as spaces in their names.

• Modules in Python can be written in external languages

such as C/C++ in Cpython, Java in Jython, .net languages
in IronPython
9/15/2011

Training Python Chapter 4

Modules Basics - Usages
• The import statement:

• The from statement:

• The from * statement

• The import happens only once

6
9/15/2011

Training Python Chapter 4

7

Modules Basics – Usages (Con’t)
• Import assigns an entire module object to a single name.
• From assigns one or more names to objects of the same names in

another module.

Be careful:
9/15/2011

Training Python Chapter 4

8

Modules Basics - namespaces
• Files generate Namespaces:
• Module statements run on the first import.
• Top-level assignments create module attributes.
• Module namespaces can be accessed via the attribute__dict__or dir(M)
• Modules are a single scope (local is global)
• Namespace nesting:
• In mod3.py:
• In mod2.py:

• In mod1.py:
9/15/2011

Training Python Chapter 4

9

Modules Basics – reloading function
• Unlike import and from:
• reload is a function in Python, not a statement.
• reload is passed an existing module object, not a name.
• reload lives in a module in Python 3.0 and must be imported itself.
• How to use:
9/15/2011

Training Python Chapter 4

10

Modules Basics – reload example
• In changer.py:

• Change global message variable:
•
9/15/2011

Training Python Chapter 4

11

Modules package
• Package __init__.py files:
• Directory:
dir0dir1dir2mod.py
• Import statement: import dir1.dir2.mod
• Rules:
• dir1 and dir2 both must contain an __init__.py file.
• dir0, the container, does not require an __init__.py file; this file will
simply be ignored if present.
• dir0, not dir0dir1, must be listed on the module search path (i.e., it must
be the home directory, or be listed in your PYTHONPATH, etc.).
• Present in tree mode:
9/15/2011

Training Python Chapter 4

12

Modules package
• Relative import:
• instructs Python to import a module named spam located in the

same package directory as the file in which this statement appears.

• Sibling import:
9/15/2011

Training Python Chapter 4

13

Modules In Advance – Data Hiding
• Minimizing from * Damage: _X and __all__
• you can prefix names with a single underscore (e.g., _X) to prevent
them from being copied out when a client imports a module’s
names with a from * statement.
• Enabling future language features
• Mixed Usage Modes: __name__ and __main__
• If the file is being run as a top-level program file, __name__ is set
to the string "__main__" when it starts.
• If the file is being imported instead, __name__ is set to the
module’s name as known by its clients
9/15/2011

Training Python Chapter 4

14

Modules in Advance (Cont’)
• In runme.py:

• Unit Tests with __name__:
• we can wrap up the self-test call in a __name__ check, so that it
will be launched only when the file is run as a top-level script, not
when it is imported
9/15/2011

Training Python Chapter 4

Modules in Advance (Cont’)
• The as Extension for import and from:

15
9/15/2011

Training Python Chapter 4

16

Module Gotchas
• Statement Order Matters in Top-Level Code
• from Copies Names but Doesn’t Link
• from * Can Obscure the Meaning of Variables

• Recursive from Imports May Not Work
• You can usually eliminate import cycles like this by careful design—
maximizing cohesion and minimizing coupling are good first steps.
THANKS FOR LISTENING
Editor: Nguyễn Đức Minh Khôi
Contact: nguyenducminhkhoi@gmail.com
Main reference: Part V – Modules
Learning Python 4th Edition – O’reilly 2010
TRAINING PYTHON
Chapter 5: CLASSES AND

OOP
9/18/2011

Training Python Chapter 5: Classes and OOP

2

Contents

Class Coding Basics
Class Coding Detail
Advanced Class topics
9/18/2011

Training Python Chapter 5: Classes and OOP

3

Class Coding Basics
• OOP program must show:
• Abstraction (or sometimes called encapsulation)
• Inheritance (vs. composition)
• Polymorphism
• Class vs. Instance Object:
• Class: Serve as instance factories. Their attributes provide
behavior—data and functions—that is inherited by all the instances
generated from them.
• Instance: Represent the concrete items in a program’s domain.
Their attributes record data that varies per specific object
9/18/2011

Training Python Chapter 5: Classes and OOP

4

Class Coding Basics (Cont’)

• Each class statement generates a new class object.
• Each time a class is called, it generates a new instance object.
• Instances are automatically linked to the classes from which they are created.
• Classes are linked to their superclasses by listing them in parentheses in a class
header line; the left-to-right order there gives the order in the tree.
9/18/2011

Training Python Chapter 5: Classes and OOP

5

Class Coding Basics – Class trees

• Notice:
• Python uses multiple inheritance: if there is more than one
superclass listed in parentheses in a class statement (like C1’s
here), their left-to-right order gives the order in which those
superclasses will be searched for attributes.
• Attributes are usually attached to classes by assignments made
within class statements, and not nested inside function def
statements.
• Attributes are usually attached to instances by assignments to a
special argument passed to functions inside classes, called self.
9/18/2011

Training Python Chapter 5: Classes and OOP

6

Class Coding Basics - Class vs. Instance
• Class Object:
• The class statement creates a class object and assigns it a name.
• Assignments inside class statements make class attributes.
• Class attributes provide object state and behavior.
• Instance Object:
• Calling a class object like a function makes a new instance object.
• Each instance object inherits class attributes and gets its own
namespace.
• Assignments to attributes of self in methods make per-instance
attributes.
9/18/2011

Training Python Chapter 5: Classes and OOP

Class Coding Basics ©
• First Example:

7
9/18/2011

Training Python Chapter 5: Classes and OOP

8

Class Coding Basics - Inheritance
• Attribute inheritance:
• Superclasses are listed in parentheses in a class header.
• Classes inherit attributes from their superclasses.
• Instances inherit attributes from all accessible classes.
• Each object.attribute reference invokes a new, independent search.
• Logic changes are made by subclassing, not by changing
superclasses.
9/18/2011

Training Python Chapter 5: Classes and OOP

9

Class Coding Basics – Inheritance ©
• Second Example:
9/18/2011

Training Python Chapter 5: Classes and OOP

10

Class Coding Details
• Class statement:

Assigning names inside the class statement makes class attributes,
and nested defs make class methods, but other assignments make
attributes, too.
• Examples:
9/18/2011

Training Python Chapter 5: Classes and OOP

Class Coding Details ©
• Method call:

• Example:

11
9/18/2011

Training Python Chapter 5: Classes and OOP

12

Class Coding Details - Inheritance
• Example:
9/18/2011

Training Python Chapter 5: Classes and OOP

13

Class Coding Details – Inheritance ©
• Class Interface Techniques:

• Real:
9/18/2011

Training Python Chapter 5: Classes and OOP

14

Class Coding Details – Inheritance ©
9/18/2011

Training Python Chapter 5: Classes and OOP

15

Class Coding Details – Inheritance ©
• Abstract superclass:
9/18/2011

Training Python Chapter 5: Classes and OOP

Class Coding Details ©

16

• Python namespaces – Assignments Classify names:
9/18/2011

Training Python Chapter 5: Classes and OOP

17

Class Coding Details – operator overloading
• Common operator overloading method:
9/18/2011

Training Python Chapter 5: Classes and OOP

18

Class Coding Details – operator overloading ©
9/18/2011

Training Python Chapter 5: Classes and OOP

19

Advanced Class topics - Relationships
• Is – relationship vs. has - relationship

In employees.py file
Express: inheritance
– is relationship
9/18/2011

Training Python Chapter 5: Classes and OOP

20

Advanced Class topics – Relationships ©

In pizzashop.py file
Express: has - relationship
9/18/2011

Training Python Chapter 5: Classes and OOP

21

Advanced Class topics – Extending built in types
• By embedding:
9/18/2011

Training Python Chapter 5: Classes and OOP

22

Advanced Class topics – Extending built in types
• By subclassing:
9/18/2011

Training Python Chapter 5: Classes and OOP

Advanced Class topics –
Diamond Inheritance
• Old and new style inheritance:

23
9/18/2011

Training Python Chapter 5: Classes and OOP

Advanced Class topics –
Diamond Inheritance
• Explicit Conflict Resolution:

24
9/18/2011

Training Python Chapter 5: Classes and OOP

25

Advanced Class topics –
static class method

• Notice:
9/18/2011

Training Python Chapter 5: Classes and OOP

26

Advanced Class topics –
static and class method
9/18/2011

Training Python Chapter 5: Classes and OOP

27

Advanced Class topics - Decorators
• Function decorators provide a way to specify special operation

modes for functions, by wrapping them in an extra layer of logic
implemented as another function.
• Syntax:

• Example:
9/18/2011

Training Python Chapter 5: Classes and OOP

28

Advanced Class topics – Decorators ©
• Class decorators are similar to function decorators, but they are run

at the end of a class statement to rebind a class name to a callable.
• Syntax:

• Example:
9/18/2011

Training Python Chapter 5: Classes and OOP

29

Advanced Class topics – Class gotchas
• Changing Class Attributes Can Have Side Effects
• Changing Mutable Class Attributes Can Have Side

Effects, Too
• Multiple Inheritance: Order Matters
• multiple inheritance works best when your mix-in classes are as

self-contained as possible—because they may be used in a variety
of contexts, they should not make assumptions about names
related to other classes in a tree.
THANKS FOR LISTENING
Editor: Nguyễn Đức Minh Khôi
Contact: nguyenducminhkhoi@gmail.com
Main reference: Part VI – Classes and OOP
Learning Python 4th Edition – O’reilly 2010
TRAINING PYTHON
INTRODUCTION TO PYTHON
(BASIC LEVEL)
Editor: Nguyễn Đức Minh Khôi
@HCMC University of Technology, September 2011
TRAINING PYTHON
Chapter 6: Exception Handling
7/13/2012

Training Python @HCMUT Summer 2012 - Chapter 6

Contents
Basic Concepts
Exception in Details

Examples

3
7/13/2012

Training Python @HCMUT Summer 2012 - Chapter 6

4

Basic Concepts
• What is Exceptions:
• Are events that can modify the flow of control through a program
• Are triggered automatically on errors, and they can be triggered and
intercepted by your code.
• What is Exception Handlers:
• Try statement
• Roles of Exceptions:
• Error Handling
• Event Notification
• Special case Handling
• Termination Actions
• Unusual control flows
7/13/2012

Training Python @HCMUT Summer 2012 - Chapter 6

Basic Concepts (cont.)
• Suppose we have the function like this:

• Default handler:

• Catching Exception:

5
7/13/2012

Training Python @HCMUT Summer 2012 - Chapter 6

Basic Concepts (cont.)
• Raising Exception:

• User define Exception:

6
7/13/2012

Training Python @HCMUT Summer 2012 - Chapter 6

Basic Concepts (cont.)
• Terminate Actions:

• Let’s compare:

7
7/13/2012

Training Python @HCMUT Summer 2012 - Chapter 6

Contents
Basic Concepts
Exception in Details

Examples

8
7/13/2012

Training Python @HCMUT Summer 2012 - Chapter 6

Exception in Details
• Try statement clauses:

9
7/13/2012

Training Python @HCMUT Summer 2012 - Chapter 6

10

Exception in Details (cont.)
• How it runs?
• If an exception does occur while the try block’s statements are running,
Python jumps back to the try and runs the statements under the first
except clause that matches the raised exception. Control resumes below
the entire try statement after the except block runs (unless the except
block raises another exception).
• If an exception happens in the try block and no except clause matches,
the exception is propagated up to the last matching try statement that
was entered in the program or, if it’s the first such statement, to the top
level of the process (in which case Python kills the program and prints a
default error message).
• If no exception occurs while the statements under the try header run,
Python runs the statements under the else line (if present), and control
then resumes below the entire try statement
7/13/2012

Training Python @HCMUT Summer 2012 - Chapter 6

Exception in Details (cont.)
• Notices:
• Except:

Vs.

• Else:
•

Vs.

11
7/13/2012

Training Python @HCMUT Summer 2012 - Chapter 6

12

Exception in Details (cont.)
• Try/finally statement:
• How it works?
• If no exception occurs while the try block is running, Python jumps back
to run the finally block and then continues execution past below the try
statement.
• If an exception does occur during the try block’s run, Python still comes
back and runs the finally block, but it then propagates the exception up
to a higher try or the top-level default handler; the program does not
resume execution below the try statement. That is, the finally block is
run even if an exception is raised, but unlike an except, the finally does
not terminate the exception—it continues being raised after the finally
block runs.
7/13/2012

Training Python @HCMUT Summer 2012 - Chapter 6

Exception in Details (cont.)
• Nested Exception Handlers:

13
7/13/2012

Training Python @HCMUT Summer 2012 - Chapter 6

Exception in Details (cont.)
• The Raise statement
• Example

• Propagating Exception with raise:

14
7/13/2012

Training Python @HCMUT Summer 2012 - Chapter 6

Exception in Details (cont.)
• The Assert Statement

• Example:

15
7/13/2012

Training Python @HCMUT Summer 2012 - Chapter 6

16

Exception in Details (cont.)
• Your own Exception Class:
superclass called General and two subclasses
called Specific1 and Specific2
Exception is the Superclass Of all Exception Class
7/13/2012

Training Python @HCMUT Summer 2012 - Chapter 6

Exception in Details
• Python Built in Exception:
• You can use directly or inherit
them to your own Exception

17
7/13/2012

Training Python @HCMUT Summer 2012 - Chapter 6

Contents
Basic Concepts
Exception in Details

Examples

18
7/13/2012

Training Python @HCMUT Summer 2012 - Chapter 6

19

Examples
• The try/finally statement examples:
• allows you to specify cleanup actions that always must occur, such as file
closes and server disconnects.
7/13/2012

Training Python @HCMUT Summer 2012 - Chapter 6

Examples (cont.)
• Unified Try Example:

20
THANKS FOR LISTENING
Editor: Nguyễn Đức Minh Khôi
Contact: nguyenducminhkhoi@gmail.com
Main reference: Part VI – Classes and OOP
Learning Python 4th Edition – O’reilly 2010

Contenu connexe

Tendances

Python final presentation kirti ppt1
Python final presentation kirti ppt1Python final presentation kirti ppt1
Python final presentation kirti ppt1Kirti Verma
 
Introduction To Python | Edureka
Introduction To Python | EdurekaIntroduction To Python | Edureka
Introduction To Python | EdurekaEdureka!
 
Python quick guide1
Python quick guide1Python quick guide1
Python quick guide1Kanchilug
 
Python: the Project, the Language and the Style
Python: the Project, the Language and the StylePython: the Project, the Language and the Style
Python: the Project, the Language and the StyleJuan-Manuel Gimeno
 
Python presentation by Monu Sharma
Python presentation by Monu SharmaPython presentation by Monu Sharma
Python presentation by Monu SharmaMayank Sharma
 
Why I Love Python
Why I Love PythonWhy I Love Python
Why I Love Pythondidip
 
Python Programming ppt
Python Programming pptPython Programming ppt
Python Programming pptismailmrribi
 
Getting started with Linux and Python by Caffe
Getting started with Linux and Python by CaffeGetting started with Linux and Python by Caffe
Getting started with Linux and Python by CaffeLihang Li
 
Phython Programming Language
Phython Programming LanguagePhython Programming Language
Phython Programming LanguageR.h. Himel
 
Python Crash Course
Python Crash CoursePython Crash Course
Python Crash CourseHaim Michael
 
Introduction to Python
Introduction to PythonIntroduction to Python
Introduction to PythonNowell Strite
 
Introduction to python
Introduction to pythonIntroduction to python
Introduction to pythonYi-Fan Chu
 

Tendances (20)

Python final presentation kirti ppt1
Python final presentation kirti ppt1Python final presentation kirti ppt1
Python final presentation kirti ppt1
 
Python
Python Python
Python
 
Introduction To Python | Edureka
Introduction To Python | EdurekaIntroduction To Python | Edureka
Introduction To Python | Edureka
 
Python - the basics
Python - the basicsPython - the basics
Python - the basics
 
Python quick guide1
Python quick guide1Python quick guide1
Python quick guide1
 
Python final ppt
Python final pptPython final ppt
Python final ppt
 
Python: the Project, the Language and the Style
Python: the Project, the Language and the StylePython: the Project, the Language and the Style
Python: the Project, the Language and the Style
 
Python presentation by Monu Sharma
Python presentation by Monu SharmaPython presentation by Monu Sharma
Python presentation by Monu Sharma
 
Training python (new Updated)
Training python (new Updated)Training python (new Updated)
Training python (new Updated)
 
Why I Love Python
Why I Love PythonWhy I Love Python
Why I Love Python
 
Basics of python
Basics of pythonBasics of python
Basics of python
 
Python Programming ppt
Python Programming pptPython Programming ppt
Python Programming ppt
 
Beginning Python Programming
Beginning Python ProgrammingBeginning Python Programming
Beginning Python Programming
 
Getting started with Linux and Python by Caffe
Getting started with Linux and Python by CaffeGetting started with Linux and Python by Caffe
Getting started with Linux and Python by Caffe
 
Phython Programming Language
Phython Programming LanguagePhython Programming Language
Phython Programming Language
 
Python Crash Course
Python Crash CoursePython Crash Course
Python Crash Course
 
Introduction to Python
Introduction to PythonIntroduction to Python
Introduction to Python
 
Python Tutorial for Beginner
Python Tutorial for BeginnerPython Tutorial for Beginner
Python Tutorial for Beginner
 
Python tutorial
Python tutorialPython tutorial
Python tutorial
 
Introduction to python
Introduction to pythonIntroduction to python
Introduction to python
 

Similaire à web programming Unit VIII complete about python by Bhavsingh Maloth

Programming with Python: Week 1
Programming with Python: Week 1Programming with Python: Week 1
Programming with Python: Week 1Ahmet Bulut
 
Introduction to python
Introduction to pythonIntroduction to python
Introduction to pythonMohammed Rafi
 
Introduction to Python for Security Professionals
Introduction to Python for Security ProfessionalsIntroduction to Python for Security Professionals
Introduction to Python for Security ProfessionalsAndrew McNicol
 
Introduction to Python Unit -1 Part .pdf
Introduction to Python Unit -1 Part .pdfIntroduction to Python Unit -1 Part .pdf
Introduction to Python Unit -1 Part .pdfVaibhavKumarSinghkal
 
Python indroduction
Python indroductionPython indroduction
Python indroductionFEG
 
PyCourse - Self driving python course
PyCourse - Self driving python coursePyCourse - Self driving python course
PyCourse - Self driving python courseEran Shlomo
 
Introduction to Python Programing
Introduction to Python ProgramingIntroduction to Python Programing
Introduction to Python Programingsameer patil
 
Python 3.5: An agile, general-purpose development language.
Python 3.5: An agile, general-purpose development language.Python 3.5: An agile, general-purpose development language.
Python 3.5: An agile, general-purpose development language.Carlos Miguel Ferreira
 
Python-Yesterday Today Tomorrow(What's new?)
Python-Yesterday Today Tomorrow(What's new?)Python-Yesterday Today Tomorrow(What's new?)
Python-Yesterday Today Tomorrow(What's new?)Mohan Arumugam
 
Python presentation of Government Engineering College Aurangabad, Bihar
Python presentation of Government Engineering College Aurangabad, BiharPython presentation of Government Engineering College Aurangabad, Bihar
Python presentation of Government Engineering College Aurangabad, BiharUttamKumar617567
 
Python Foundation – A programmer's introduction to Python concepts & style
Python Foundation – A programmer's introduction to Python concepts & stylePython Foundation – A programmer's introduction to Python concepts & style
Python Foundation – A programmer's introduction to Python concepts & styleKevlin Henney
 

Similaire à web programming Unit VIII complete about python by Bhavsingh Maloth (20)

Python Course In Chandigarh
Python Course In ChandigarhPython Course In Chandigarh
Python Course In Chandigarh
 
Programming with Python: Week 1
Programming with Python: Week 1Programming with Python: Week 1
Programming with Python: Week 1
 
Introduction to python
Introduction to pythonIntroduction to python
Introduction to python
 
Introduction to Python for Security Professionals
Introduction to Python for Security ProfessionalsIntroduction to Python for Security Professionals
Introduction to Python for Security Professionals
 
Introduction to Python Unit -1 Part .pdf
Introduction to Python Unit -1 Part .pdfIntroduction to Python Unit -1 Part .pdf
Introduction to Python Unit -1 Part .pdf
 
Python indroduction
Python indroductionPython indroduction
Python indroduction
 
PyCourse - Self driving python course
PyCourse - Self driving python coursePyCourse - Self driving python course
PyCourse - Self driving python course
 
Python intro
Python introPython intro
Python intro
 
Introduction to Python Programing
Introduction to Python ProgramingIntroduction to Python Programing
Introduction to Python Programing
 
Python 3.5: An agile, general-purpose development language.
Python 3.5: An agile, general-purpose development language.Python 3.5: An agile, general-purpose development language.
Python 3.5: An agile, general-purpose development language.
 
Python PPT 50.pptx
Python PPT 50.pptxPython PPT 50.pptx
Python PPT 50.pptx
 
Python-Yesterday Today Tomorrow(What's new?)
Python-Yesterday Today Tomorrow(What's new?)Python-Yesterday Today Tomorrow(What's new?)
Python-Yesterday Today Tomorrow(What's new?)
 
01 python introduction
01 python introduction 01 python introduction
01 python introduction
 
Python presentation of Government Engineering College Aurangabad, Bihar
Python presentation of Government Engineering College Aurangabad, BiharPython presentation of Government Engineering College Aurangabad, Bihar
Python presentation of Government Engineering College Aurangabad, Bihar
 
Python Demo.pptx
Python Demo.pptxPython Demo.pptx
Python Demo.pptx
 
PHYTON-REPORT.pdf
PHYTON-REPORT.pdfPHYTON-REPORT.pdf
PHYTON-REPORT.pdf
 
What is python
What is pythonWhat is python
What is python
 
Python 01.pptx
Python 01.pptxPython 01.pptx
Python 01.pptx
 
Python Foundation – A programmer's introduction to Python concepts & style
Python Foundation – A programmer's introduction to Python concepts & stylePython Foundation – A programmer's introduction to Python concepts & style
Python Foundation – A programmer's introduction to Python concepts & style
 
Python Demo.pptx
Python Demo.pptxPython Demo.pptx
Python Demo.pptx
 

Plus de Bhavsingh Maloth

web programming Unit VI PPT by Bhavsingh Maloth
web programming Unit VI PPT  by Bhavsingh Malothweb programming Unit VI PPT  by Bhavsingh Maloth
web programming Unit VI PPT by Bhavsingh MalothBhavsingh Maloth
 
web programming UNIT VIII python by Bhavsingh Maloth
web programming UNIT VIII python by Bhavsingh Malothweb programming UNIT VIII python by Bhavsingh Maloth
web programming UNIT VIII python by Bhavsingh MalothBhavsingh Maloth
 
Web programming unit IIII XML &DOM NOTES BY BHAVSINGH MALOTH
Web programming unit IIII XML &DOM NOTES BY BHAVSINGH MALOTHWeb programming unit IIII XML &DOM NOTES BY BHAVSINGH MALOTH
Web programming unit IIII XML &DOM NOTES BY BHAVSINGH MALOTHBhavsingh Maloth
 
WEB PROGRAMMING UNIT IV NOTES BY BHAVSINGH MALOTH
WEB PROGRAMMING UNIT IV NOTES BY BHAVSINGH MALOTHWEB PROGRAMMING UNIT IV NOTES BY BHAVSINGH MALOTH
WEB PROGRAMMING UNIT IV NOTES BY BHAVSINGH MALOTHBhavsingh Maloth
 
WEB PROGRAMMING UNIT VIII BY BHAVSINGH MALOTH
WEB PROGRAMMING UNIT VIII BY BHAVSINGH MALOTHWEB PROGRAMMING UNIT VIII BY BHAVSINGH MALOTH
WEB PROGRAMMING UNIT VIII BY BHAVSINGH MALOTHBhavsingh Maloth
 
WEB PROGRAMMING UNIT VI BY BHAVSINGH MALOTH
WEB PROGRAMMING UNIT VI BY BHAVSINGH MALOTHWEB PROGRAMMING UNIT VI BY BHAVSINGH MALOTH
WEB PROGRAMMING UNIT VI BY BHAVSINGH MALOTHBhavsingh Maloth
 
WEB PROGRAMMING UNIT V BY BHAVSINGH MALOTH
WEB PROGRAMMING UNIT V BY BHAVSINGH MALOTHWEB PROGRAMMING UNIT V BY BHAVSINGH MALOTH
WEB PROGRAMMING UNIT V BY BHAVSINGH MALOTHBhavsingh Maloth
 
WEB PROGRAMMING UNIT II BY BHAVSINGH MALOTH
WEB PROGRAMMING UNIT II BY BHAVSINGH MALOTHWEB PROGRAMMING UNIT II BY BHAVSINGH MALOTH
WEB PROGRAMMING UNIT II BY BHAVSINGH MALOTHBhavsingh Maloth
 
Web programming UNIT II by Bhavsingh Maloth
Web programming UNIT II by Bhavsingh MalothWeb programming UNIT II by Bhavsingh Maloth
Web programming UNIT II by Bhavsingh MalothBhavsingh Maloth
 
Xml dom & sax by bhavsingh maloth
Xml dom & sax by bhavsingh malothXml dom & sax by bhavsingh maloth
Xml dom & sax by bhavsingh malothBhavsingh Maloth
 
Appscpolytechniclecturersg.s.paper2007
Appscpolytechniclecturersg.s.paper2007Appscpolytechniclecturersg.s.paper2007
Appscpolytechniclecturersg.s.paper2007Bhavsingh Maloth
 
Appscpolytechniclecturersg.s.paper2007
Appscpolytechniclecturersg.s.paper2007Appscpolytechniclecturersg.s.paper2007
Appscpolytechniclecturersg.s.paper2007Bhavsingh Maloth
 
98286173 government-polytechnic-lecturer-exam-paper-2012
98286173 government-polytechnic-lecturer-exam-paper-201298286173 government-polytechnic-lecturer-exam-paper-2012
98286173 government-polytechnic-lecturer-exam-paper-2012Bhavsingh Maloth
 
Web Programming UNIT VIII notes
Web Programming UNIT VIII notesWeb Programming UNIT VIII notes
Web Programming UNIT VIII notesBhavsingh Maloth
 

Plus de Bhavsingh Maloth (20)

web programming Unit VI PPT by Bhavsingh Maloth
web programming Unit VI PPT  by Bhavsingh Malothweb programming Unit VI PPT  by Bhavsingh Maloth
web programming Unit VI PPT by Bhavsingh Maloth
 
web programming UNIT VIII python by Bhavsingh Maloth
web programming UNIT VIII python by Bhavsingh Malothweb programming UNIT VIII python by Bhavsingh Maloth
web programming UNIT VIII python by Bhavsingh Maloth
 
Web programming unit IIII XML &DOM NOTES BY BHAVSINGH MALOTH
Web programming unit IIII XML &DOM NOTES BY BHAVSINGH MALOTHWeb programming unit IIII XML &DOM NOTES BY BHAVSINGH MALOTH
Web programming unit IIII XML &DOM NOTES BY BHAVSINGH MALOTH
 
WEB PROGRAMMING UNIT IV NOTES BY BHAVSINGH MALOTH
WEB PROGRAMMING UNIT IV NOTES BY BHAVSINGH MALOTHWEB PROGRAMMING UNIT IV NOTES BY BHAVSINGH MALOTH
WEB PROGRAMMING UNIT IV NOTES BY BHAVSINGH MALOTH
 
WEB PROGRAMMING UNIT VIII BY BHAVSINGH MALOTH
WEB PROGRAMMING UNIT VIII BY BHAVSINGH MALOTHWEB PROGRAMMING UNIT VIII BY BHAVSINGH MALOTH
WEB PROGRAMMING UNIT VIII BY BHAVSINGH MALOTH
 
WEB PROGRAMMING UNIT VI BY BHAVSINGH MALOTH
WEB PROGRAMMING UNIT VI BY BHAVSINGH MALOTHWEB PROGRAMMING UNIT VI BY BHAVSINGH MALOTH
WEB PROGRAMMING UNIT VI BY BHAVSINGH MALOTH
 
WEB PROGRAMMING UNIT V BY BHAVSINGH MALOTH
WEB PROGRAMMING UNIT V BY BHAVSINGH MALOTHWEB PROGRAMMING UNIT V BY BHAVSINGH MALOTH
WEB PROGRAMMING UNIT V BY BHAVSINGH MALOTH
 
WEB PROGRAMMING UNIT II BY BHAVSINGH MALOTH
WEB PROGRAMMING UNIT II BY BHAVSINGH MALOTHWEB PROGRAMMING UNIT II BY BHAVSINGH MALOTH
WEB PROGRAMMING UNIT II BY BHAVSINGH MALOTH
 
Web programming UNIT II by Bhavsingh Maloth
Web programming UNIT II by Bhavsingh MalothWeb programming UNIT II by Bhavsingh Maloth
Web programming UNIT II by Bhavsingh Maloth
 
Xml dom & sax by bhavsingh maloth
Xml dom & sax by bhavsingh malothXml dom & sax by bhavsingh maloth
Xml dom & sax by bhavsingh maloth
 
Polytechnic jan 6 2012
Polytechnic jan 6 2012Polytechnic jan 6 2012
Polytechnic jan 6 2012
 
Appscpolytechniclecturersg.s.paper2007
Appscpolytechniclecturersg.s.paper2007Appscpolytechniclecturersg.s.paper2007
Appscpolytechniclecturersg.s.paper2007
 
Appsc poly key 2013
Appsc poly key 2013Appsc poly key 2013
Appsc poly key 2013
 
Appscpolytechniclecturersg.s.paper2007
Appscpolytechniclecturersg.s.paper2007Appscpolytechniclecturersg.s.paper2007
Appscpolytechniclecturersg.s.paper2007
 
Appsc poly key 2013
Appsc poly key 2013Appsc poly key 2013
Appsc poly key 2013
 
98286173 government-polytechnic-lecturer-exam-paper-2012
98286173 government-polytechnic-lecturer-exam-paper-201298286173 government-polytechnic-lecturer-exam-paper-2012
98286173 government-polytechnic-lecturer-exam-paper-2012
 
Unit vii wp ppt
Unit vii wp pptUnit vii wp ppt
Unit vii wp ppt
 
Unit VI
Unit VI Unit VI
Unit VI
 
Wp unit III
Wp unit IIIWp unit III
Wp unit III
 
Web Programming UNIT VIII notes
Web Programming UNIT VIII notesWeb Programming UNIT VIII notes
Web Programming UNIT VIII notes
 

Dernier

Prescribed medication order and communication skills.pptx
Prescribed medication order and communication skills.pptxPrescribed medication order and communication skills.pptx
Prescribed medication order and communication skills.pptxraviapr7
 
CapTechU Doctoral Presentation -March 2024 slides.pptx
CapTechU Doctoral Presentation -March 2024 slides.pptxCapTechU Doctoral Presentation -March 2024 slides.pptx
CapTechU Doctoral Presentation -March 2024 slides.pptxCapitolTechU
 
Human-AI Co-Creation of Worked Examples for Programming Classes
Human-AI Co-Creation of Worked Examples for Programming ClassesHuman-AI Co-Creation of Worked Examples for Programming Classes
Human-AI Co-Creation of Worked Examples for Programming ClassesMohammad Hassany
 
UKCGE Parental Leave Discussion March 2024
UKCGE Parental Leave Discussion March 2024UKCGE Parental Leave Discussion March 2024
UKCGE Parental Leave Discussion March 2024UKCGE
 
Patterns of Written Texts Across Disciplines.pptx
Patterns of Written Texts Across Disciplines.pptxPatterns of Written Texts Across Disciplines.pptx
Patterns of Written Texts Across Disciplines.pptxMYDA ANGELICA SUAN
 
Maximizing Impact_ Nonprofit Website Planning, Budgeting, and Design.pdf
Maximizing Impact_ Nonprofit Website Planning, Budgeting, and Design.pdfMaximizing Impact_ Nonprofit Website Planning, Budgeting, and Design.pdf
Maximizing Impact_ Nonprofit Website Planning, Budgeting, and Design.pdfTechSoup
 
Diploma in Nursing Admission Test Question Solution 2023.pdf
Diploma in Nursing Admission Test Question Solution 2023.pdfDiploma in Nursing Admission Test Question Solution 2023.pdf
Diploma in Nursing Admission Test Question Solution 2023.pdfMohonDas
 
How to Use api.constrains ( ) in Odoo 17
How to Use api.constrains ( ) in Odoo 17How to Use api.constrains ( ) in Odoo 17
How to Use api.constrains ( ) in Odoo 17Celine George
 
Easter in the USA presentation by Chloe.
Easter in the USA presentation by Chloe.Easter in the USA presentation by Chloe.
Easter in the USA presentation by Chloe.EnglishCEIPdeSigeiro
 
Clinical Pharmacy Introduction to Clinical Pharmacy, Concept of clinical pptx
Clinical Pharmacy  Introduction to Clinical Pharmacy, Concept of clinical pptxClinical Pharmacy  Introduction to Clinical Pharmacy, Concept of clinical pptx
Clinical Pharmacy Introduction to Clinical Pharmacy, Concept of clinical pptxraviapr7
 
CHUYÊN ĐỀ DẠY THÊM TIẾNG ANH LỚP 11 - GLOBAL SUCCESS - NĂM HỌC 2023-2024 - HK...
CHUYÊN ĐỀ DẠY THÊM TIẾNG ANH LỚP 11 - GLOBAL SUCCESS - NĂM HỌC 2023-2024 - HK...CHUYÊN ĐỀ DẠY THÊM TIẾNG ANH LỚP 11 - GLOBAL SUCCESS - NĂM HỌC 2023-2024 - HK...
CHUYÊN ĐỀ DẠY THÊM TIẾNG ANH LỚP 11 - GLOBAL SUCCESS - NĂM HỌC 2023-2024 - HK...Nguyen Thanh Tu Collection
 
What is the Future of QuickBooks DeskTop?
What is the Future of QuickBooks DeskTop?What is the Future of QuickBooks DeskTop?
What is the Future of QuickBooks DeskTop?TechSoup
 
2024.03.23 What do successful readers do - Sandy Millin for PARK.pptx
2024.03.23 What do successful readers do - Sandy Millin for PARK.pptx2024.03.23 What do successful readers do - Sandy Millin for PARK.pptx
2024.03.23 What do successful readers do - Sandy Millin for PARK.pptxSandy Millin
 
3.21.24 The Origins of Black Power.pptx
3.21.24  The Origins of Black Power.pptx3.21.24  The Origins of Black Power.pptx
3.21.24 The Origins of Black Power.pptxmary850239
 
Patient Counselling. Definition of patient counseling; steps involved in pati...
Patient Counselling. Definition of patient counseling; steps involved in pati...Patient Counselling. Definition of patient counseling; steps involved in pati...
Patient Counselling. Definition of patient counseling; steps involved in pati...raviapr7
 
P4C x ELT = P4ELT: Its Theoretical Background (Kanazawa, 2024 March).pdf
P4C x ELT = P4ELT: Its Theoretical Background (Kanazawa, 2024 March).pdfP4C x ELT = P4ELT: Its Theoretical Background (Kanazawa, 2024 March).pdf
P4C x ELT = P4ELT: Its Theoretical Background (Kanazawa, 2024 March).pdfYu Kanazawa / Osaka University
 
AUDIENCE THEORY -- FANDOM -- JENKINS.pptx
AUDIENCE THEORY -- FANDOM -- JENKINS.pptxAUDIENCE THEORY -- FANDOM -- JENKINS.pptx
AUDIENCE THEORY -- FANDOM -- JENKINS.pptxiammrhaywood
 
Practical Research 1: Lesson 8 Writing the Thesis Statement.pptx
Practical Research 1: Lesson 8 Writing the Thesis Statement.pptxPractical Research 1: Lesson 8 Writing the Thesis Statement.pptx
Practical Research 1: Lesson 8 Writing the Thesis Statement.pptxKatherine Villaluna
 

Dernier (20)

Prescribed medication order and communication skills.pptx
Prescribed medication order and communication skills.pptxPrescribed medication order and communication skills.pptx
Prescribed medication order and communication skills.pptx
 
CapTechU Doctoral Presentation -March 2024 slides.pptx
CapTechU Doctoral Presentation -March 2024 slides.pptxCapTechU Doctoral Presentation -March 2024 slides.pptx
CapTechU Doctoral Presentation -March 2024 slides.pptx
 
Personal Resilience in Project Management 2 - TV Edit 1a.pdf
Personal Resilience in Project Management 2 - TV Edit 1a.pdfPersonal Resilience in Project Management 2 - TV Edit 1a.pdf
Personal Resilience in Project Management 2 - TV Edit 1a.pdf
 
Human-AI Co-Creation of Worked Examples for Programming Classes
Human-AI Co-Creation of Worked Examples for Programming ClassesHuman-AI Co-Creation of Worked Examples for Programming Classes
Human-AI Co-Creation of Worked Examples for Programming Classes
 
UKCGE Parental Leave Discussion March 2024
UKCGE Parental Leave Discussion March 2024UKCGE Parental Leave Discussion March 2024
UKCGE Parental Leave Discussion March 2024
 
Patterns of Written Texts Across Disciplines.pptx
Patterns of Written Texts Across Disciplines.pptxPatterns of Written Texts Across Disciplines.pptx
Patterns of Written Texts Across Disciplines.pptx
 
Maximizing Impact_ Nonprofit Website Planning, Budgeting, and Design.pdf
Maximizing Impact_ Nonprofit Website Planning, Budgeting, and Design.pdfMaximizing Impact_ Nonprofit Website Planning, Budgeting, and Design.pdf
Maximizing Impact_ Nonprofit Website Planning, Budgeting, and Design.pdf
 
Diploma in Nursing Admission Test Question Solution 2023.pdf
Diploma in Nursing Admission Test Question Solution 2023.pdfDiploma in Nursing Admission Test Question Solution 2023.pdf
Diploma in Nursing Admission Test Question Solution 2023.pdf
 
How to Use api.constrains ( ) in Odoo 17
How to Use api.constrains ( ) in Odoo 17How to Use api.constrains ( ) in Odoo 17
How to Use api.constrains ( ) in Odoo 17
 
Easter in the USA presentation by Chloe.
Easter in the USA presentation by Chloe.Easter in the USA presentation by Chloe.
Easter in the USA presentation by Chloe.
 
Clinical Pharmacy Introduction to Clinical Pharmacy, Concept of clinical pptx
Clinical Pharmacy  Introduction to Clinical Pharmacy, Concept of clinical pptxClinical Pharmacy  Introduction to Clinical Pharmacy, Concept of clinical pptx
Clinical Pharmacy Introduction to Clinical Pharmacy, Concept of clinical pptx
 
CHUYÊN ĐỀ DẠY THÊM TIẾNG ANH LỚP 11 - GLOBAL SUCCESS - NĂM HỌC 2023-2024 - HK...
CHUYÊN ĐỀ DẠY THÊM TIẾNG ANH LỚP 11 - GLOBAL SUCCESS - NĂM HỌC 2023-2024 - HK...CHUYÊN ĐỀ DẠY THÊM TIẾNG ANH LỚP 11 - GLOBAL SUCCESS - NĂM HỌC 2023-2024 - HK...
CHUYÊN ĐỀ DẠY THÊM TIẾNG ANH LỚP 11 - GLOBAL SUCCESS - NĂM HỌC 2023-2024 - HK...
 
What is the Future of QuickBooks DeskTop?
What is the Future of QuickBooks DeskTop?What is the Future of QuickBooks DeskTop?
What is the Future of QuickBooks DeskTop?
 
2024.03.23 What do successful readers do - Sandy Millin for PARK.pptx
2024.03.23 What do successful readers do - Sandy Millin for PARK.pptx2024.03.23 What do successful readers do - Sandy Millin for PARK.pptx
2024.03.23 What do successful readers do - Sandy Millin for PARK.pptx
 
3.21.24 The Origins of Black Power.pptx
3.21.24  The Origins of Black Power.pptx3.21.24  The Origins of Black Power.pptx
3.21.24 The Origins of Black Power.pptx
 
Patient Counselling. Definition of patient counseling; steps involved in pati...
Patient Counselling. Definition of patient counseling; steps involved in pati...Patient Counselling. Definition of patient counseling; steps involved in pati...
Patient Counselling. Definition of patient counseling; steps involved in pati...
 
P4C x ELT = P4ELT: Its Theoretical Background (Kanazawa, 2024 March).pdf
P4C x ELT = P4ELT: Its Theoretical Background (Kanazawa, 2024 March).pdfP4C x ELT = P4ELT: Its Theoretical Background (Kanazawa, 2024 March).pdf
P4C x ELT = P4ELT: Its Theoretical Background (Kanazawa, 2024 March).pdf
 
Finals of Kant get Marx 2.0 : a general politics quiz
Finals of Kant get Marx 2.0 : a general politics quizFinals of Kant get Marx 2.0 : a general politics quiz
Finals of Kant get Marx 2.0 : a general politics quiz
 
AUDIENCE THEORY -- FANDOM -- JENKINS.pptx
AUDIENCE THEORY -- FANDOM -- JENKINS.pptxAUDIENCE THEORY -- FANDOM -- JENKINS.pptx
AUDIENCE THEORY -- FANDOM -- JENKINS.pptx
 
Practical Research 1: Lesson 8 Writing the Thesis Statement.pptx
Practical Research 1: Lesson 8 Writing the Thesis Statement.pptxPractical Research 1: Lesson 8 Writing the Thesis Statement.pptx
Practical Research 1: Lesson 8 Writing the Thesis Statement.pptx
 

web programming Unit VIII complete about python by Bhavsingh Maloth

  • 1. TRAINING PYTHON INTRODUCTION TO PYTHON (BASIC LEVEL) Editor: Nguyễn Đức Minh Khôi @HCMC University of Technology, September 2011
  • 2. 9/2/2011 Training Python Chapte 0: Introduction to Python TRAINING PYTHON Chapter 0: INTRODUCTION TO PYTHON 1
  • 3. 9/2/2011 Training Python Chapte 0: Introduction to Python 2 CONTENTS Python in general How Python program runs? How to run Python?
  • 4. 9/2/2011 Training Python Chapte 0: Introduction to Python 3 Python in general • What is python? • High level programming language • Emphasize on code readability • Very clear syntax + large and comprehensive standard library • Use of indentation for block delimiters • Multiprogramming paradigm: OO, imperative, functional, procedural, reflective • A fully dynamic type system and automatic memory management • Scripting language + standalone executable program + interpreter • Can run on many platform: Windows, Linux, Mactonish • Updates: • Newest version: 3.2.2 (CPython, JPython, IronPython) • Website: www.python.org
  • 5. 9/2/2011 Training Python Chapte 0: Introduction to Python 4 Python in general (Cont’) • Advantages: • Software quality • Developer productivity • Program portability • Support libraries • Component integration • Enjoyment • Disadvantages: • not always be as fast as that of compiled languages such as C and C++
  • 6. 9/2/2011 Training Python Chapte 0: Introduction to Python Python in general (Cont’) • Applications of python: 5
  • 7. 9/2/2011 Training Python Chapte 0: Introduction to Python Python in general (Cont’) • Python’s Capability: • System Programming • GUI • Internet Scripting • Component Integration • Database Programming • Rapid Prototyping • Numeric and Scientific Programming • Gaming, Images, Serial Ports, XML, Robots, and More 6
  • 8. 9/2/2011 Training Python Chapte 0: Introduction to Python 7 How Python program runs? Notice: pure Python code runs at speeds somewhere between those of a traditional compiled language and a traditional interpreted language
  • 9. 9/2/2011 Training Python Chapte 0: Introduction to Python How to run Python? • Install Python 3.2.2: • Go to website: http://www.python.org/download/ and download the latest version of Python • Run and install follow the instructions of the .msi file • If you successfully install, you will see this picture: • Coding Python: • Not IDE support: use notepad++ http://notepad-plus-plus.org/ • Use IDE support: Eclipse (3.7) or Netbeans (7.0) 8
  • 10. 9/2/2011 Training Python Chapte 0: Introduction to Python 9 How to run Python? (Cont’) • Install Eclipse: follow the instructions from this website: http://wiki.eclipse.org/FAQ_Where_do_I_get_and_install_Eclipse%3F (you should download the Eclipse Classics version) • Install Pydev plugin for eclipse: follow this instruction: http://pydev.org/manual_101_install.html
  • 11. 9/2/2011 Training Python Chapte 0: Introduction to Python 10 THANKS FOR LISTENING Editor: Nguyễn Đức Minh Khôi Contact: nguyenducminhkhoi@gmail.com Main reference: Part I – Getting Started Learning Python – O’reilly
  • 12. TRAINING PYTHON CHAPTER 1: TYPES AND OPERATIONS
  • 14. 5/22/2011 Training Python 3 Lists • Ordered collections of arbitrary objects • Accessed by offset • Variable-length, heterogeneous, and arbitrarily nestable • Of the category “mutable sequence” • Arrays of object references
  • 16. 5/22/2011 Training Python 5 Lists literals and operations (cont’)
  • 17. 5/22/2011 Training Python 6 Dictionaries • Accessed by key, not offset • Accessed by key, not offset • Variable-length, heterogeneous, and arbitrarily nestable • Of the category “mutable mapping” • Tables of object references (hash tables)
  • 20. 5/22/2011 Training Python 9 Tuples • Ordered collections of arbitrary objects • Accessed by offset • Of the category “immutable sequence” • Fixed-length, heterogeneous, and arbitrarily nestable • Arrays of object references
  • 23. 5/22/2011 Training Python Files – common operations 12
  • 24. 2 NUMERIC TYPES • Integers and floating-point numbers • Complex numbers • Fixed-precision decimal numbers • Rational fraction numbers • Sets • Booleans • Unlimited integer precision • A variety of numeric built-ins and modules
  • 27. Dynamic Typing • Variables, Objects, References: • Variables are entries in a system table, with spaces for links to objects. • Objects are pieces of allocated memory, with enough space to represent the values for which they stand. • References are automatically followed pointers from variables to objects.
  • 28. Dynamic Typing (Cont’) - Shared references • Immutable types:
  • 29. Dynamic Typing (Cont’) - Shared references • Mutable types: • Notices: • It’s also just the default: if you don’t want such behavior, you can request that Python copy objects instead of making references.
  • 30. Dynamic Typing (Cont’) - Shared references • Notices (next): • “is” function returns False if the names point to equivalent but different objects, as is the case when we run two different literal expressions. • Small integers and strings are cached and reused, though, is tells us they reference the same single object.
  • 31. 5/22/2011 Summary • Object just classification Training Python 13
  • 32. 5/22/2011 Training Python 14 Summary (con’t) • Object Flexibility • Lists, dictionaries, and tuples can hold any kind of object. • Lists, dictionaries, and tuples can be arbitrarily nested. • Lists and dictionaries can dynamically grow and shrink. • Object copy • Slice expressions with empty limits (L[:]) copy sequences. • The dictionary and set copy method (X.copy()) copies a dictionary or set. • Some built-in functions, such as list, make copies (list(L)). • The copy standard library module makes full copies.
  • 33. 9/2/2011 Learning Python Chapter 1 1 THANKS FOR LISTENING Editor: Nguy n Đ c Minh Khôi Contact: nguyenducminhkhoi@gmail.com Main reference: Part II – Types and Operations Learning Python – O’reilly
  • 34. 9/2/2011 Learning Python Chapter 2 TRAINING PYTHON STATEMENTS AND SYNTAX 1
  • 35. 9/2/2011 Learning Python Chapter 2 Content Statements Assignment, Expression, Print Conditional statements Loop statements Iterations and comprehensions 2
  • 36. 9/2/2011 Learning Python Chapter 2 Python program structures: • Programs are composed of modules. • Modules contain statements. • Statements contain expressions. • Expressions create and process objects. 3
  • 37. 9/2/2011 Learning Python Chapter 2 Python statements 4
  • 38. 9/2/2011 Learning Python Chapter 2 Python statements (Cont’) 5
  • 39. 9/2/2011 Learning Python Chapter 2 Python statements (Cont’) 6
  • 40. 9/2/2011 Learning Python Chapter 2 Assignment Statements Assignment Properties: • Assignments create object references • Names are created when first assigned • Names must be assigned before being referenced • Some operations perform assignments implicitly Assignment Statement Forms: 7
  • 41. 9/2/2011 Learning Python Chapter 2 8 Variable name rules (opt) • Syntax: (underscore or letter) + (any number of letters, digits, or underscores) • Case matters: SPAM is not the same as spam • Reserved words are off-limits
  • 42. 9/2/2011 Learning Python Chapter 2 Expression Statements 9
  • 43. 9/2/2011 Print Operations • Call format • Example: Learning Python Chapter 2 10
  • 44. 9/2/2011 Learning Python Chapter 2 Conditional Statements - IF • General Format: • The if/else ternary expression: • Example: 11
  • 45. 9/2/2011 Learning Python Chapter 2 12 IF Statements - Truth tests (opt) Conditional expression: • Any nonzero number or nonempty object is true. • Zero numbers, empty objects, and the special object None are considered false. • Comparisons and equality tests are applied recursively to data structures. • Comparisons and equality tests return True or False (custom versions of 1 and 0). • Boolean “and” and “or” operators return a true or false operand object.
  • 46. 9/2/2011 Learning Python Chapter 2 13 IF Statements - Truth tests (opt) (Cont) • “and” and “or” operands:
  • 47. 9/2/2011 Learning Python Chapter 2 14 Loop Statements – while statements • General while format: • Notice:
  • 48. 9/2/2011 Learning Python Chapter 2 15 Loop Statements – for statements • General Format: • Loop Coding Techniques: • The built-in range function produces a series of successively higher integers, which can be used as indexes in a for. • The built-in zip function returns a series of parallel-item tuples, which can be used to traverse multiple sequences in a for. • Notice: for loops typically run quicker than while-based counter loops, it’s to your advantage to use tools like these that allow you to use for when possible.
  • 49. 9/2/2011 Learning Python Chapter 2 Loop statements - examples 16
  • 50. 9/2/2011 Learning Python Chapter 2 17 Iterations and comprehensions • Iterable: • an object is considered iterable if it is either a physically stored sequence or an object that produces one result at a time in the context of an iteration tool like a for loop. • iterable objects include both physical sequences and virtual sequences computed on demand. • Iterations: • Any object with a __next__ method to advance to a next result, which raises StopIteration at the end of the series of results, is considered iterable in Python. • Example:
  • 51. 9/2/2011 Learning Python Chapter 2 List comprehension • Example: • (x + 10): arbitrary expression • (for x in L): iterable object • Extend List Comprehension: 18
  • 52. 9/2/2011 Learning Python Chapter 2 19 New Iterator in Python 3.0 • Iterators associated: • built-in type :set, list, dictionary, tuple, file • Dictionary method: keys, values, items • Built-in function: range (multiple iterator), map, zip, filter (single) • Examples:
  • 53. 9/2/2011 Learning Python Chapter 2 Iterators examples (cont’) 20
  • 54. 9/2/2011 Learning Python Chapter 2 21 THANKS FOR LISTENING Editor: Nguyễn Đức Minh Khôi Contact: nguyenducminhkhoi@gmail.com Main reference: Part III – Statements and Syntax Learning Python – O’reilly
  • 55. 9/6/2011 Training Python Chapter 3 TRAINING PYTHON Chapter 3: FUNCTION 1
  • 56. 9/6/2011 Training Python Chapter 3 2 CONTENTS Function Basics Scope Arguments Function Advanced Iterations and Comprehension Advanced
  • 57. 9/6/2011 Training Python Chapter 3 Function Basics • Function: A function is a device that groups a set of statements so they can be run more than once in a program. • Why use?: • Maximizing code reuse and minimizing redundancy • Procedural decomposition 3
  • 58. 9/6/2011 Training Python Chapter 3 4 Function Basics – def Statements • General format: • Use “def” statements:
  • 59. 9/6/2011 Training Python Chapter 3 Function Basics – Examples 5
  • 60. 9/6/2011 Training Python Chapter 3 6 Scopes • Three different scopes • If a variable is assigned inside a def, it is local to that function. • If a variable is assigned in an enclosing def, it is nonlocal to nested functions. • If a variable is assigned outside all defs, it is global to the entire file. • Notice: • All names assigned inside a function def statement (or a lambda, an expression we’ll meet later) are locals by default. • Functions can freely use names as-signed in syntactically enclosing functions and the global scope, but they must declare such nonlocals and globals in order to change them.
  • 61. 9/6/2011 Training Python Chapter 3 Scopes – the LEGB rules 7
  • 62. 9/6/2011 Training Python Chapter 3 8 Scopes – examples Global names: X, func Local names: Y, Z # The Built – in Scopes
  • 63. 9/6/2011 Training Python Chapter 3 Scopes – Global statements • Global Statement: • Other ways to access Globals: 9
  • 64. 9/6/2011 Training Python Chapter 3 10 Scopes – Global statements(Cont’)
  • 65. 9/6/2011 Training Python Chapter 3 11 Scopes – Nested functions • Factory function • These terms refer to a function object that remembers values in enclosing scopes regardless of whether those scopes are still present in memory.
  • 66. 9/6/2011 Training Python Chapter 3 Scopes – Nested scope (Cont’) • Nested scope and lambda: 12
  • 67. 9/6/2011 Training Python Chapter 3 13 Scopes – Nonlocal statements • The nonlocal statement: • Is a close cousin to global • Like global: nonlocal declares that a name will be changed in an enclosing scope. • Unlike global: • nonlocal applies to a name in an enclosing function’s scope, not the global module scope outside all defs. • nonlocal names must already exist in the enclosing function’s scope when declared • Format:
  • 68. 9/6/2011 Training Python Chapter 3 14 Scopes – Nonlocal statements (Con’t)
  • 69. 9/6/2011 Training Python Chapter 3 15 Arguments – Passing Basics • Arguments are passed by automatically assigning objects to local • • • • variable names. Assigning to argument names inside a function does not affect the caller. Changing a mutable object argument in a function may impact the caller. Immutable arguments are effectively passed “by value.” Mutable arguments are effectively passed “by pointer.”
  • 70. 9/6/2011 Training Python Chapter 3 16 Arguments – Matching Modes • Keyword-only arguments: arguments that must be passed by keyword only and will never be filled in by a positional argument.
  • 71. 9/6/2011 Training Python Chapter 3 Arguments - Examples 17
  • 72. 9/6/2011 Training Python Chapter 3 Arguments – Examples (Cont’) 18
  • 73. 9/6/2011 Training Python Chapter 3 Arguments – Bonus Points 19
  • 74. 9/6/2011 Training Python Chapter 3 20 Function Advanced • General guidelines: • Coupling: use arguments for inputs and return for outputs. • Coupling: use global variables only when truly necessary. • Coupling: don’t change mutable arguments unless the caller expects it. • Cohesion: each function should have a single, unified purpose. • Size: each function should be relatively small. • Coupling: avoid changing variables in another module file directly.
  • 75. 9/6/2011 Training Python Chapter 3 Function Advanced - Recursions • Examples: • Alternatives: 21
  • 76. 9/6/2011 Training Python Chapter 3 22 Function Advanced – Lambda Expression • Lambda format: • Use lambda for: • inline a function definition • defer execution of a piece of code • Notices: • lambda is an expression, not a statement • lambda’s body is a single expression, not a block of statements. • If you have larger logic to code, use def; lambda is for small pieces of inline code. On the other hand, you may find these techniques useful in moderation • Examples:
  • 77. 9/6/2011 Training Python Chapter 3 Lambda Expression (Cont’) • Logic within lambda function: • Nested lambda: • Used with map function: • Used with filter function: • Used with reduce function: 23
  • 78. 9/6/2011 Training Python Chapter 3 24 Iterations and Comprehension Part 2 • List Comprehension: • Vs. Map: • Vs. filter: • Vs. Nested for:
  • 79. 9/6/2011 Training Python Chapter 3 25 Iterations and Comprehension Part 2 • Generators: • Generator functions: are coded as normal def statements but use yield statements to return results one at a time, suspending and resuming their state between each. • Generator expressions: are similar to the list comprehensions of the prior section, but they return an object that produces results on demand instead of building a result list. • Generator functions:
  • 80. 9/6/2011 Training Python Chapter 3 26 Iterations and Comprehension Part 2 • Generator Expression:
  • 81. 9/6/2011 Training Python Chapter 3 3.0 Comprehension Syntax 27
  • 82. 9/6/2011 Training Python Chapter 3 28 Function Pitfall • “List comprehensions were nearly twice as fast as equivalent for loop statements, and map was slightly quicker than list comprehensions when mapping a built-in function such as abs (absolute value)” • Python detects locals statically, when it compiles the def’s code, rather than by noticing assignments as they happen at runtime.
  • 83. 9/6/2011 Learning Python Chapter 2 29 THANKS FOR LISTENING Editor: Nguyễn Đức Minh Khôi Contact: nguyenducminhkhoi@gmail.com Main reference: Part IV – Functions Learning Python 4th Edition – O’reilly 2010
  • 85. 9/15/2011 Training Python Chapter 4 Contents Modules Basics Modules Package Modules in advance 2
  • 86. 9/15/2011 Training Python Chapter 4 3 Modules Basics • Modules are process with: • import: Lets a client (importer) fetch a module as a whole • from: Allows clients to fetch particular names from a module • imp.reload: Provides a way to reload a module’s code without stopping Python • Why use Modules? • Code reuse • System namespace partitioning • Implementing service or data
  • 87. 9/15/2011 Training Python Chapter 4 4 Modules Basics – import statements • How imports work? 1. Find the module’s file. 2. Compile it to byte code (if needed). 3. Run the module’s code to build the objects it defines. • The Module Search Path: 1. The home directory of the program 2. PYTHONPATH directories (if set) 3. Standard library directories 4. The contents of any .pth files (if present)
  • 88. 9/15/2011 Training Python Chapter 4 5 Modules Basics – create Modules • In fact, both the names of module files and the names of directories used in package must conform to the rules for variable names: • They may, for instance, contain only letters, digits, and underscores. • Package directories also cannot contain platform-specific syntax such as spaces in their names. • Modules in Python can be written in external languages such as C/C++ in Cpython, Java in Jython, .net languages in IronPython
  • 89. 9/15/2011 Training Python Chapter 4 Modules Basics - Usages • The import statement: • The from statement: • The from * statement • The import happens only once 6
  • 90. 9/15/2011 Training Python Chapter 4 7 Modules Basics – Usages (Con’t) • Import assigns an entire module object to a single name. • From assigns one or more names to objects of the same names in another module. Be careful:
  • 91. 9/15/2011 Training Python Chapter 4 8 Modules Basics - namespaces • Files generate Namespaces: • Module statements run on the first import. • Top-level assignments create module attributes. • Module namespaces can be accessed via the attribute__dict__or dir(M) • Modules are a single scope (local is global) • Namespace nesting: • In mod3.py: • In mod2.py: • In mod1.py:
  • 92. 9/15/2011 Training Python Chapter 4 9 Modules Basics – reloading function • Unlike import and from: • reload is a function in Python, not a statement. • reload is passed an existing module object, not a name. • reload lives in a module in Python 3.0 and must be imported itself. • How to use:
  • 93. 9/15/2011 Training Python Chapter 4 10 Modules Basics – reload example • In changer.py: • Change global message variable: •
  • 94. 9/15/2011 Training Python Chapter 4 11 Modules package • Package __init__.py files: • Directory: dir0dir1dir2mod.py • Import statement: import dir1.dir2.mod • Rules: • dir1 and dir2 both must contain an __init__.py file. • dir0, the container, does not require an __init__.py file; this file will simply be ignored if present. • dir0, not dir0dir1, must be listed on the module search path (i.e., it must be the home directory, or be listed in your PYTHONPATH, etc.). • Present in tree mode:
  • 95. 9/15/2011 Training Python Chapter 4 12 Modules package • Relative import: • instructs Python to import a module named spam located in the same package directory as the file in which this statement appears. • Sibling import:
  • 96. 9/15/2011 Training Python Chapter 4 13 Modules In Advance – Data Hiding • Minimizing from * Damage: _X and __all__ • you can prefix names with a single underscore (e.g., _X) to prevent them from being copied out when a client imports a module’s names with a from * statement. • Enabling future language features • Mixed Usage Modes: __name__ and __main__ • If the file is being run as a top-level program file, __name__ is set to the string "__main__" when it starts. • If the file is being imported instead, __name__ is set to the module’s name as known by its clients
  • 97. 9/15/2011 Training Python Chapter 4 14 Modules in Advance (Cont’) • In runme.py: • Unit Tests with __name__: • we can wrap up the self-test call in a __name__ check, so that it will be launched only when the file is run as a top-level script, not when it is imported
  • 98. 9/15/2011 Training Python Chapter 4 Modules in Advance (Cont’) • The as Extension for import and from: 15
  • 99. 9/15/2011 Training Python Chapter 4 16 Module Gotchas • Statement Order Matters in Top-Level Code • from Copies Names but Doesn’t Link • from * Can Obscure the Meaning of Variables • Recursive from Imports May Not Work • You can usually eliminate import cycles like this by careful design— maximizing cohesion and minimizing coupling are good first steps.
  • 100. THANKS FOR LISTENING Editor: Nguyễn Đức Minh Khôi Contact: nguyenducminhkhoi@gmail.com Main reference: Part V – Modules Learning Python 4th Edition – O’reilly 2010
  • 101. TRAINING PYTHON Chapter 5: CLASSES AND OOP
  • 102. 9/18/2011 Training Python Chapter 5: Classes and OOP 2 Contents Class Coding Basics Class Coding Detail Advanced Class topics
  • 103. 9/18/2011 Training Python Chapter 5: Classes and OOP 3 Class Coding Basics • OOP program must show: • Abstraction (or sometimes called encapsulation) • Inheritance (vs. composition) • Polymorphism • Class vs. Instance Object: • Class: Serve as instance factories. Their attributes provide behavior—data and functions—that is inherited by all the instances generated from them. • Instance: Represent the concrete items in a program’s domain. Their attributes record data that varies per specific object
  • 104. 9/18/2011 Training Python Chapter 5: Classes and OOP 4 Class Coding Basics (Cont’) • Each class statement generates a new class object. • Each time a class is called, it generates a new instance object. • Instances are automatically linked to the classes from which they are created. • Classes are linked to their superclasses by listing them in parentheses in a class header line; the left-to-right order there gives the order in the tree.
  • 105. 9/18/2011 Training Python Chapter 5: Classes and OOP 5 Class Coding Basics – Class trees • Notice: • Python uses multiple inheritance: if there is more than one superclass listed in parentheses in a class statement (like C1’s here), their left-to-right order gives the order in which those superclasses will be searched for attributes. • Attributes are usually attached to classes by assignments made within class statements, and not nested inside function def statements. • Attributes are usually attached to instances by assignments to a special argument passed to functions inside classes, called self.
  • 106. 9/18/2011 Training Python Chapter 5: Classes and OOP 6 Class Coding Basics - Class vs. Instance • Class Object: • The class statement creates a class object and assigns it a name. • Assignments inside class statements make class attributes. • Class attributes provide object state and behavior. • Instance Object: • Calling a class object like a function makes a new instance object. • Each instance object inherits class attributes and gets its own namespace. • Assignments to attributes of self in methods make per-instance attributes.
  • 107. 9/18/2011 Training Python Chapter 5: Classes and OOP Class Coding Basics © • First Example: 7
  • 108. 9/18/2011 Training Python Chapter 5: Classes and OOP 8 Class Coding Basics - Inheritance • Attribute inheritance: • Superclasses are listed in parentheses in a class header. • Classes inherit attributes from their superclasses. • Instances inherit attributes from all accessible classes. • Each object.attribute reference invokes a new, independent search. • Logic changes are made by subclassing, not by changing superclasses.
  • 109. 9/18/2011 Training Python Chapter 5: Classes and OOP 9 Class Coding Basics – Inheritance © • Second Example:
  • 110. 9/18/2011 Training Python Chapter 5: Classes and OOP 10 Class Coding Details • Class statement: Assigning names inside the class statement makes class attributes, and nested defs make class methods, but other assignments make attributes, too. • Examples:
  • 111. 9/18/2011 Training Python Chapter 5: Classes and OOP Class Coding Details © • Method call: • Example: 11
  • 112. 9/18/2011 Training Python Chapter 5: Classes and OOP 12 Class Coding Details - Inheritance • Example:
  • 113. 9/18/2011 Training Python Chapter 5: Classes and OOP 13 Class Coding Details – Inheritance © • Class Interface Techniques: • Real:
  • 114. 9/18/2011 Training Python Chapter 5: Classes and OOP 14 Class Coding Details – Inheritance ©
  • 115. 9/18/2011 Training Python Chapter 5: Classes and OOP 15 Class Coding Details – Inheritance © • Abstract superclass:
  • 116. 9/18/2011 Training Python Chapter 5: Classes and OOP Class Coding Details © 16 • Python namespaces – Assignments Classify names:
  • 117. 9/18/2011 Training Python Chapter 5: Classes and OOP 17 Class Coding Details – operator overloading • Common operator overloading method:
  • 118. 9/18/2011 Training Python Chapter 5: Classes and OOP 18 Class Coding Details – operator overloading ©
  • 119. 9/18/2011 Training Python Chapter 5: Classes and OOP 19 Advanced Class topics - Relationships • Is – relationship vs. has - relationship In employees.py file Express: inheritance – is relationship
  • 120. 9/18/2011 Training Python Chapter 5: Classes and OOP 20 Advanced Class topics – Relationships © In pizzashop.py file Express: has - relationship
  • 121. 9/18/2011 Training Python Chapter 5: Classes and OOP 21 Advanced Class topics – Extending built in types • By embedding:
  • 122. 9/18/2011 Training Python Chapter 5: Classes and OOP 22 Advanced Class topics – Extending built in types • By subclassing:
  • 123. 9/18/2011 Training Python Chapter 5: Classes and OOP Advanced Class topics – Diamond Inheritance • Old and new style inheritance: 23
  • 124. 9/18/2011 Training Python Chapter 5: Classes and OOP Advanced Class topics – Diamond Inheritance • Explicit Conflict Resolution: 24
  • 125. 9/18/2011 Training Python Chapter 5: Classes and OOP 25 Advanced Class topics – static class method • Notice:
  • 126. 9/18/2011 Training Python Chapter 5: Classes and OOP 26 Advanced Class topics – static and class method
  • 127. 9/18/2011 Training Python Chapter 5: Classes and OOP 27 Advanced Class topics - Decorators • Function decorators provide a way to specify special operation modes for functions, by wrapping them in an extra layer of logic implemented as another function. • Syntax: • Example:
  • 128. 9/18/2011 Training Python Chapter 5: Classes and OOP 28 Advanced Class topics – Decorators © • Class decorators are similar to function decorators, but they are run at the end of a class statement to rebind a class name to a callable. • Syntax: • Example:
  • 129. 9/18/2011 Training Python Chapter 5: Classes and OOP 29 Advanced Class topics – Class gotchas • Changing Class Attributes Can Have Side Effects • Changing Mutable Class Attributes Can Have Side Effects, Too • Multiple Inheritance: Order Matters • multiple inheritance works best when your mix-in classes are as self-contained as possible—because they may be used in a variety of contexts, they should not make assumptions about names related to other classes in a tree.
  • 130. THANKS FOR LISTENING Editor: Nguyễn Đức Minh Khôi Contact: nguyenducminhkhoi@gmail.com Main reference: Part VI – Classes and OOP Learning Python 4th Edition – O’reilly 2010
  • 131. TRAINING PYTHON INTRODUCTION TO PYTHON (BASIC LEVEL) Editor: Nguyễn Đức Minh Khôi @HCMC University of Technology, September 2011
  • 132. TRAINING PYTHON Chapter 6: Exception Handling
  • 133. 7/13/2012 Training Python @HCMUT Summer 2012 - Chapter 6 Contents Basic Concepts Exception in Details Examples 3
  • 134. 7/13/2012 Training Python @HCMUT Summer 2012 - Chapter 6 4 Basic Concepts • What is Exceptions: • Are events that can modify the flow of control through a program • Are triggered automatically on errors, and they can be triggered and intercepted by your code. • What is Exception Handlers: • Try statement • Roles of Exceptions: • Error Handling • Event Notification • Special case Handling • Termination Actions • Unusual control flows
  • 135. 7/13/2012 Training Python @HCMUT Summer 2012 - Chapter 6 Basic Concepts (cont.) • Suppose we have the function like this: • Default handler: • Catching Exception: 5
  • 136. 7/13/2012 Training Python @HCMUT Summer 2012 - Chapter 6 Basic Concepts (cont.) • Raising Exception: • User define Exception: 6
  • 137. 7/13/2012 Training Python @HCMUT Summer 2012 - Chapter 6 Basic Concepts (cont.) • Terminate Actions: • Let’s compare: 7
  • 138. 7/13/2012 Training Python @HCMUT Summer 2012 - Chapter 6 Contents Basic Concepts Exception in Details Examples 8
  • 139. 7/13/2012 Training Python @HCMUT Summer 2012 - Chapter 6 Exception in Details • Try statement clauses: 9
  • 140. 7/13/2012 Training Python @HCMUT Summer 2012 - Chapter 6 10 Exception in Details (cont.) • How it runs? • If an exception does occur while the try block’s statements are running, Python jumps back to the try and runs the statements under the first except clause that matches the raised exception. Control resumes below the entire try statement after the except block runs (unless the except block raises another exception). • If an exception happens in the try block and no except clause matches, the exception is propagated up to the last matching try statement that was entered in the program or, if it’s the first such statement, to the top level of the process (in which case Python kills the program and prints a default error message). • If no exception occurs while the statements under the try header run, Python runs the statements under the else line (if present), and control then resumes below the entire try statement
  • 141. 7/13/2012 Training Python @HCMUT Summer 2012 - Chapter 6 Exception in Details (cont.) • Notices: • Except: Vs. • Else: • Vs. 11
  • 142. 7/13/2012 Training Python @HCMUT Summer 2012 - Chapter 6 12 Exception in Details (cont.) • Try/finally statement: • How it works? • If no exception occurs while the try block is running, Python jumps back to run the finally block and then continues execution past below the try statement. • If an exception does occur during the try block’s run, Python still comes back and runs the finally block, but it then propagates the exception up to a higher try or the top-level default handler; the program does not resume execution below the try statement. That is, the finally block is run even if an exception is raised, but unlike an except, the finally does not terminate the exception—it continues being raised after the finally block runs.
  • 143. 7/13/2012 Training Python @HCMUT Summer 2012 - Chapter 6 Exception in Details (cont.) • Nested Exception Handlers: 13
  • 144. 7/13/2012 Training Python @HCMUT Summer 2012 - Chapter 6 Exception in Details (cont.) • The Raise statement • Example • Propagating Exception with raise: 14
  • 145. 7/13/2012 Training Python @HCMUT Summer 2012 - Chapter 6 Exception in Details (cont.) • The Assert Statement • Example: 15
  • 146. 7/13/2012 Training Python @HCMUT Summer 2012 - Chapter 6 16 Exception in Details (cont.) • Your own Exception Class: superclass called General and two subclasses called Specific1 and Specific2 Exception is the Superclass Of all Exception Class
  • 147. 7/13/2012 Training Python @HCMUT Summer 2012 - Chapter 6 Exception in Details • Python Built in Exception: • You can use directly or inherit them to your own Exception 17
  • 148. 7/13/2012 Training Python @HCMUT Summer 2012 - Chapter 6 Contents Basic Concepts Exception in Details Examples 18
  • 149. 7/13/2012 Training Python @HCMUT Summer 2012 - Chapter 6 19 Examples • The try/finally statement examples: • allows you to specify cleanup actions that always must occur, such as file closes and server disconnects.
  • 150. 7/13/2012 Training Python @HCMUT Summer 2012 - Chapter 6 Examples (cont.) • Unified Try Example: 20
  • 151. THANKS FOR LISTENING Editor: Nguyễn Đức Minh Khôi Contact: nguyenducminhkhoi@gmail.com Main reference: Part VI – Classes and OOP Learning Python 4th Edition – O’reilly 2010