Download - Introduction to Python
![Page 1: Introduction to Python](https://reader036.vdocument.in/reader036/viewer/2022062319/555a67d3d8b42a972b8b4936/html5/thumbnails/1.jpg)
Gianluca Costa
Introduction to Python
![Page 2: Introduction to Python](https://reader036.vdocument.in/reader036/viewer/2022062319/555a67d3d8b42a972b8b4936/html5/thumbnails/2.jpg)
Main traits
Interpreted
Cross-technology
ExtensibleElegant
VHLL
![Page 3: Introduction to Python](https://reader036.vdocument.in/reader036/viewer/2022062319/555a67d3d8b42a972b8b4936/html5/thumbnails/3.jpg)
Timeline
1991 2000 2008
Python 1.0 Python 2 Python 3
2014
Python 3.4
Python 2.7
![Page 4: Introduction to Python](https://reader036.vdocument.in/reader036/viewer/2022062319/555a67d3d8b42a972b8b4936/html5/thumbnails/4.jpg)
The execution model
x = 10
print(x)
Myscript.pyThe interpreter
executeslines of code
following the flow
![Page 5: Introduction to Python](https://reader036.vdocument.in/reader036/viewer/2022062319/555a67d3d8b42a972b8b4936/html5/thumbnails/5.jpg)
Running Python scripts
● python <script path>
● On Windows: shell associations
● On Linux: traditional #!
![Page 6: Introduction to Python](https://reader036.vdocument.in/reader036/viewer/2022062319/555a67d3d8b42a972b8b4936/html5/thumbnails/6.jpg)
Trying out Python
Python's interpreter is interactive, too!
![Page 7: Introduction to Python](https://reader036.vdocument.in/reader036/viewer/2022062319/555a67d3d8b42a972b8b4936/html5/thumbnails/7.jpg)
Variables
● x = 10
● Later, you can write:
x = “Hello”
![Page 8: Introduction to Python](https://reader036.vdocument.in/reader036/viewer/2022062319/555a67d3d8b42a972b8b4936/html5/thumbnails/8.jpg)
Names are remote controls
10
Hellox
x = 10
x = “Hello”
![Page 9: Introduction to Python](https://reader036.vdocument.in/reader036/viewer/2022062319/555a67d3d8b42a972b8b4936/html5/thumbnails/9.jpg)
Assignment
The key to Python's naming is the assignment operator
X = 101)Expression evaluation
2)Name creation & binding
![Page 10: Introduction to Python](https://reader036.vdocument.in/reader036/viewer/2022062319/555a67d3d8b42a972b8b4936/html5/thumbnails/10.jpg)
Basic data types
● bool: True, False● str: “Cip”, 'Cip', r“\d+”, “““Multiline string”””● unicode: u“Ciop”, u'Ciop', ur“\d+”,
u“““Multiline”””● int: 2 ** 90● float: 5.3● complex: 8 + 7j
![Page 11: Introduction to Python](https://reader036.vdocument.in/reader036/viewer/2022062319/555a67d3d8b42a972b8b4936/html5/thumbnails/11.jpg)
None
● X = None
![Page 12: Introduction to Python](https://reader036.vdocument.in/reader036/viewer/2022062319/555a67d3d8b42a972b8b4936/html5/thumbnails/12.jpg)
Inspecting a Python object
● type(obj)● dir(obj)● isinstance(obj, <type>)● obj is None● obj is not None
![Page 13: Introduction to Python](https://reader036.vdocument.in/reader036/viewer/2022062319/555a67d3d8b42a972b8b4936/html5/thumbnails/13.jpg)
Strings: a warning
● In Python 2, str and unicode
● In Python 3, str and bytes
![Page 14: Introduction to Python](https://reader036.vdocument.in/reader036/viewer/2022062319/555a67d3d8b42a972b8b4936/html5/thumbnails/14.jpg)
Collections
● Arrays do not exist in Python (^__^!)● list: [], [90, 100, 474, “Yogi”]● tuple: (), (2,), (4.3, 12.1)● dict: {}, {“Alpha”: 90, “Beta”: 2, 15: 20}● set: set(), {1, 2, 3}
![Page 15: Introduction to Python](https://reader036.vdocument.in/reader036/viewer/2022062319/555a67d3d8b42a972b8b4936/html5/thumbnails/15.jpg)
Flow control
● if / elif / else● while● try / except / finally● raise● with● for● yield● pass
![Page 16: Introduction to Python](https://reader036.vdocument.in/reader036/viewer/2022062319/555a67d3d8b42a972b8b4936/html5/thumbnails/16.jpg)
For in Python
● No C-style for
● Python only uses iterations on collections:– for i in range(10):
print(i)
![Page 17: Introduction to Python](https://reader036.vdocument.in/reader036/viewer/2022062319/555a67d3d8b42a972b8b4936/html5/thumbnails/17.jpg)
List comprehension
● topStudents = [student for student in students if student.average >= 85
]● coordinates = [
(x + 5, y - 2)for x in range(1, 11)for y in range(1, 6)
]
coordinates = [ ]
for x in range(1, 11):for y in range(1, 6):
coordinates.append((x + 5, y – 2)
)
![Page 18: Introduction to Python](https://reader036.vdocument.in/reader036/viewer/2022062319/555a67d3d8b42a972b8b4936/html5/thumbnails/18.jpg)
Exceptions
try:raise MyException(“Epic!”)
except (ExcType1, ExcType2) as ex:pass
except ExcType3:pass
except:pass
finally:pass
![Page 19: Introduction to Python](https://reader036.vdocument.in/reader036/viewer/2022062319/555a67d3d8b42a972b8b4936/html5/thumbnails/19.jpg)
The WITH statement
with open(“readme.txt”, “r”) as myFile: for line in myFile:
#Process line hereprint(line)
![Page 20: Introduction to Python](https://reader036.vdocument.in/reader036/viewer/2022062319/555a67d3d8b42a972b8b4936/html5/thumbnails/20.jpg)
Functions
● def f(x, y):return x + y
● A new function object is created and the name “f” gets bound to it.
![Page 21: Introduction to Python](https://reader036.vdocument.in/reader036/viewer/2022062319/555a67d3d8b42a972b8b4936/html5/thumbnails/21.jpg)
Functions as objects
● def f(x, y):return x + y
● h = f
● h(90, 100)
![Page 22: Introduction to Python](https://reader036.vdocument.in/reader036/viewer/2022062319/555a67d3d8b42a972b8b4936/html5/thumbnails/22.jpg)
No overloading in Python
● In Python, def creates a function object and binds a name to it!
● Cannot do overloading!!! X___X!
![Page 23: Introduction to Python](https://reader036.vdocument.in/reader036/viewer/2022062319/555a67d3d8b42a972b8b4936/html5/thumbnails/23.jpg)
Parameters VS Argument
● Parameter = variable in a function signature. It's a placeholder for the actual value
● Argument = actual value passed when invoking the function
![Page 24: Introduction to Python](https://reader036.vdocument.in/reader036/viewer/2022062319/555a67d3d8b42a972b8b4936/html5/thumbnails/24.jpg)
Function parameters
● Standard parameters: f(x, y)● Default values: f(x, y, z = 90)● Arbitrary sequence: f(*args)● Keyword params: f(**kwargs)
● They can all be introduced, in this order:f(x, y, z = 90, *args, **kwargs)
![Page 25: Introduction to Python](https://reader036.vdocument.in/reader036/viewer/2022062319/555a67d3d8b42a972b8b4936/html5/thumbnails/25.jpg)
Function arguments● Given a function f(x, y)...● ...pass by position: f(9, 10)● ...pass by name: f(y = 10, x = 9)● ...unpack a list of arguments:
– myParamsSequence = [9, 10]
– f(*myParamsSequence)
● ...pass a map of arguments:– myParamsMap = { “x”: 9, “y”: 10” }
– f(**myParamsMap)
![Page 26: Introduction to Python](https://reader036.vdocument.in/reader036/viewer/2022062319/555a67d3d8b42a972b8b4936/html5/thumbnails/26.jpg)
Lambdas
● myFunction = lambda x, y: x + y
● myFunction(90, 100)
![Page 27: Introduction to Python](https://reader036.vdocument.in/reader036/viewer/2022062319/555a67d3d8b42a972b8b4936/html5/thumbnails/27.jpg)
Classes
● class Panda(object):pass #can be used for classes, too
● In Python 3, you can just write:
class Panda:pass
![Page 28: Introduction to Python](https://reader036.vdocument.in/reader036/viewer/2022062319/555a67d3d8b42a972b8b4936/html5/thumbnails/28.jpg)
Creating methods
● class Panda(object):def sayHello(self):
print(“Hello! ^__^!”)
● self is the first parameter of instance methods, and it's passed as an implicit argument! It refers to the current instance, just like this in Java/C#.
![Page 29: Introduction to Python](https://reader036.vdocument.in/reader036/viewer/2022062319/555a67d3d8b42a972b8b4936/html5/thumbnails/29.jpg)
No overloading for methods
● Methods are bound functions
● Methods do not support overloading
![Page 30: Introduction to Python](https://reader036.vdocument.in/reader036/viewer/2022062319/555a67d3d8b42a972b8b4936/html5/thumbnails/30.jpg)
Fields and constructor
● class Panda(object):def __init__(self, name):
self._name = nameself._picnicChests = 0
def addPicnicChest(self, picnicChest):self._picnicChests += 1
def getName(self):return self._name
![Page 31: Introduction to Python](https://reader036.vdocument.in/reader036/viewer/2022062319/555a67d3d8b42a972b8b4936/html5/thumbnails/31.jpg)
No access control in Python
If a member of an object should not be used by other objects, just prepend “_” to its name.
For example:
● self._privateField = 0● def _privateMethod(self):
pass
![Page 32: Introduction to Python](https://reader036.vdocument.in/reader036/viewer/2022062319/555a67d3d8b42a972b8b4936/html5/thumbnails/32.jpg)
Instantiating an object
● yogi = Panda(“Yogi”)
● print(yogi.name)● yogi.addPicnicChest(myPicnicChest)
![Page 33: Introduction to Python](https://reader036.vdocument.in/reader036/viewer/2022062319/555a67d3d8b42a972b8b4936/html5/thumbnails/33.jpg)
Class fields
● class Panda(object):_population = 0
def __init__(self):Panda._population += 1
● print(Panda._population)print(yogi._population)
![Page 34: Introduction to Python](https://reader036.vdocument.in/reader036/viewer/2022062319/555a67d3d8b42a972b8b4936/html5/thumbnails/34.jpg)
Class fields - Caveat
● yogi = Panda(“Yogi”)● print(yogi._population)● yogi._population = 10● print(Panda._population) #Output == ?
![Page 35: Introduction to Python](https://reader036.vdocument.in/reader036/viewer/2022062319/555a67d3d8b42a972b8b4936/html5/thumbnails/35.jpg)
Object's name resolution
3. Super namespaces
2. Class namespace
1. Object namespace
… = obj.name
![Page 36: Introduction to Python](https://reader036.vdocument.in/reader036/viewer/2022062319/555a67d3d8b42a972b8b4936/html5/thumbnails/36.jpg)
Multiple inheritance
● Python does not define explicit interfaces...● ...but it supports multiple inheritance!
● class Panda(Bear, VeryCuteAnimal):pass
![Page 37: Introduction to Python](https://reader036.vdocument.in/reader036/viewer/2022062319/555a67d3d8b42a972b8b4936/html5/thumbnails/37.jpg)
Diamond resolution
Just too difficult to learn! ^__^''''
![Page 38: Introduction to Python](https://reader036.vdocument.in/reader036/viewer/2022062319/555a67d3d8b42a972b8b4936/html5/thumbnails/38.jpg)
Explicit method resolution
● Given an object instance, how to call the method of a specific superclass?
– Super1.f(obj, <args>)
– Super2.f(obj, <args>)
![Page 39: Introduction to Python](https://reader036.vdocument.in/reader036/viewer/2022062319/555a67d3d8b42a972b8b4936/html5/thumbnails/39.jpg)
Overriding methods
● Python supports overriding!● But how to call the version provided by the
superclass?
![Page 40: Introduction to Python](https://reader036.vdocument.in/reader036/viewer/2022062319/555a67d3d8b42a972b8b4936/html5/thumbnails/40.jpg)
super()
● super(CurrentClassName, self).f(<args>)
● In Python 3:super().f(<args>)
● Not mandatory (you can use explicit method resolution instead)
![Page 41: Introduction to Python](https://reader036.vdocument.in/reader036/viewer/2022062319/555a67d3d8b42a972b8b4936/html5/thumbnails/41.jpg)
Static methods
● class Panda(object):@staticmethoddef myStaticMethod(x, y):
return x+y● Static methods can be called via the class
or via any instance
![Page 42: Introduction to Python](https://reader036.vdocument.in/reader036/viewer/2022062319/555a67d3d8b42a972b8b4936/html5/thumbnails/42.jpg)
Class methods
● class Bear(object):@classmethoddef f(cls, x, y):
return x + y● They can be called via class or instance
![Page 43: Introduction to Python](https://reader036.vdocument.in/reader036/viewer/2022062319/555a67d3d8b42a972b8b4936/html5/thumbnails/43.jpg)
Operator overloading
● To overload “+”– def __add__(self, other):
return ...
● There are several operators available
![Page 44: Introduction to Python](https://reader036.vdocument.in/reader036/viewer/2022062319/555a67d3d8b42a972b8b4936/html5/thumbnails/44.jpg)
String representations (v. 2.x)
● __repr__(self)● __str__(self)● __unicode__(self)
![Page 45: Introduction to Python](https://reader036.vdocument.in/reader036/viewer/2022062319/555a67d3d8b42a972b8b4936/html5/thumbnails/45.jpg)
String representations (v. 3.x)
● __repr__(self)● __bytes__(self)● __str__(self)
![Page 46: Introduction to Python](https://reader036.vdocument.in/reader036/viewer/2022062319/555a67d3d8b42a972b8b4936/html5/thumbnails/46.jpg)
Equality and hashcode
● __eq__(self, other) and __neq__(self, other). Both should be implemented.
● __hash__(self) returns the hash code
![Page 47: Introduction to Python](https://reader036.vdocument.in/reader036/viewer/2022062319/555a67d3d8b42a972b8b4936/html5/thumbnails/47.jpg)
Comparisons
● Binary operators: __gt__, __gte__, __lt__, __lte__
● Alternatively, __cmp__ behaves just like Java's compareTo()
![Page 48: Introduction to Python](https://reader036.vdocument.in/reader036/viewer/2022062319/555a67d3d8b42a972b8b4936/html5/thumbnails/48.jpg)
Modules
● Python files are modules...
● ...but not all modules are files! ^__^!
● PYTHONPATH
![Page 49: Introduction to Python](https://reader036.vdocument.in/reader036/viewer/2022062319/555a67d3d8b42a972b8b4936/html5/thumbnails/49.jpg)
Importing a module
● import re
● from re import compile
● from re import * (good just while learning)
![Page 50: Introduction to Python](https://reader036.vdocument.in/reader036/viewer/2022062319/555a67d3d8b42a972b8b4936/html5/thumbnails/50.jpg)
Module caching and reloading
● Importing a module executes it only the first time
● The module cache is sys.modules
● reload() reloads a module
● .pyc files to optimize loading in future sessions
![Page 51: Introduction to Python](https://reader036.vdocument.in/reader036/viewer/2022062319/555a67d3d8b42a972b8b4936/html5/thumbnails/51.jpg)
Packages
● Python supports packages!
● Directory structure
● __init__.py
● Within a package, use relative import!
![Page 52: Introduction to Python](https://reader036.vdocument.in/reader036/viewer/2022062319/555a67d3d8b42a972b8b4936/html5/thumbnails/52.jpg)
Further execution options
● Py2exe for Windows● PyInstaller for Windows & Unix● Jython● IronPython● Boo