Python Training: A Basic Overview
Python Training: A Basic Overview
A basic overview
Functions
• Built-in functions
• Lambda functions
Modules
Packages
– Q: Why?
– A: Reference Semantics
hello('Greetings')
def hello_1(greeting, name): Using named parameters. In this case
print ('%s, %s!' % (greeting, name)) the order of the arguments does not
# The order here doesn't matter at all: matter.
hello_1(name='world', greeting='Hello')
Unnamed functions
It is just like any other python program file with extension .py
A new file appears in this case \path\<module>.pyc. The file with the .pyc
extension is a compiled Python file for fast loading.
Python will look for modules in its system path. So either put the modules in
the right place or tell python where to look!
import sys
sys.path.append('c:/python')
Packages are used to organize modules. While a module is stored in a file with
the file name extension .py, a package is a directory.
To make Python treat it as a package, the folder must contain a file (module)
named __init__.py
File/Directory Description
~/python/ Directory in PYTHONPATH
~/python/drawing/ Package directory (drawing package)
~/python/drawing/__init__.py Package code ("drawing module")
~/python/drawing/colors.py colors module
~/python/drawing/shapes.py shapes module
~/python/drawing/gradient.py gradient module
~/python/drawing/text.py text module
~/python/drawing/image.py image module
Python supports both free form and fixed form files – text and binary
open() returns a file object, and is most commonly used with two arguments:
open(filename, mode)
Value Description
Modes: 'r' Read mode
'w' Write mode
'a' Append mode
'b' Binary mode (added to other mode)
'+' Read/write mode (added to other mode)
f = open(r'C:\text\somefile.txt')
Attribute Description
File Object attributes
With statement
– The advantage is that the file will be automatically closed after the indented
block after the with has finished execution
Copy a file
fobj_in = open("example.txt")
fobj_out = open("excopy.txt","w")
i=1
for line in fobj_in:
print(line.rstrip())
fobj_out.write(str(i) + ": " + line)
i=i+1
fobj_in.close()
fobj_out.close()
Methods
class Point:
""" Point class represents and manipulates x,y coords. """
def __init__(self, x=0): self.x = x
def x_square(self): return self.x ** 2
p = Point(2)
print p.x_square()
Operator Overloading
class Point:
def __init__(self, x=0, y=0):
self.x = x
self.y = y
def __add__(self, other):
return Point(self.x + other.x, self.y + other.y)
def __mul__(self, other):
if isinstance(other, Point):
return Point(self.x * other.x, self.y * other.y)
else:
return Point(self.x * other, self.y * other)
def __rmul__(self, other):
return Point(self.x * other, self.y * other)
def __repr__(self):
return "({0}, {1})".format(self.x, self.y)
p1 = Point(2,3)
p2 = Point(3,4)
print p1 + p2 #prints (5, 7)
print p1 * p2 #prints (6, 12)
print p1 * 2 #prints (4, 6)
print 2 * p2 #prints (6, 8)
>>> d = Dog('Fido')
>>> e = Dog('Buddy')
>>> d.kind # shared by all dogs
'canine'
>>> e.kind # shared by all dogs
'canine'
>>> d.name # unique to d
'Fido'
>>> e.name # unique to e
'Buddy'
>>> d = Dog('Fido')
>>> e = Dog('Buddy')
>>> d.add_trick('roll over')
>>> e.add_trick('play dead')
>>> d.tricks # unexpectedly shared by all dogs
['roll over', 'play dead']
>>> d = Dog('Fido')
>>> e = Dog('Buddy')
>>> d.add_trick('roll over')
>>> e.add_trick('play dead')
>>> d.tricks
['roll over']
>>> e.tricks
['play dead‘]
Right-hand-side equivalents for all binary operators exist (__radd__, __rsub__, __rmul__, __rdiv__, ...).
They are called when class instance is on r-h-s of operator:
-- a + 3 calls __add__(a, 3) -- 3 + a calls __radd__(a, 3)
Method Description
__init__(self, args) Instance initialization (on construction)
__del__(self) Called on object demise (refcount becomes 0)
__repr__(self) repr() and `...` conversions
__str__(self) str() and print statement
__sizeof__(self) Returns amount of memory used by object, in bytes (called by sys.getsizeof()).
__format__(self, format_spec) format() and str.format() conversions
__cmp__(self,other) Compares self to other and returns <0, 0, or >0. Implements >, <, == etc...
__index__(self) Allows using any object as integer index (e.g. for slicing). Must return a single integer or
long integer value.
__lt__(self, other) Called for self < other comparisons. Can return anything, or can raise an exception.
__le__(self, other) Called for self <= other comparisons. Can return anything, or can raise an exception.
__gt__(self, other) Called for self > other comparisons. Can return anything, or can raise an exception.
__ge__(self, other) Called for self >= other comparisons. Can return anything, or can raise an exception.
__eq__(self, other) Called for self == other comparisons. Can return anything, or can raise an exception.
__ne__(self, other) Called for self != other (and self <> other) comparisons. Can return anything, or can raise
an exception.
Method Description
__hash__(self) Compute a 32 bit hash code; hash() and dictionary ops. Since 2.5 can also return a long integer, in
which case the hash of that value will be taken.Since 2.6 can set __hash__ = None to void class
inherited hashability.
__nonzero__(self) Returns 0 or 1 for truth value testing. when this method is not defined, __len__() is called if
defined; otherwise all class instances are considered "true".
__getattr__(self,name) Called when attribute lookup doesn't find name. See also __getattribute__.
__getattribute__( self, name) Same as __getattr__ but always called whenever the attribute name is accessed.
__dir__( self) Returns the list of names of valid attributes for the object. Called by builtin function dir(), but
ignored unless __getattr__or __getattribute__ is defined.
__setattr__(self, name, value) Called when setting an attribute (inside, don't use "self.name = value", use instead
"self.__dict__[name] = value")
__enter__(self) For use with context managers, i.e. when entering the block in a with-statement.
The with statement binds this method's return value to the as object.
__exit__(self, type, value, tra When exiting the block of a with-statement. If no errors occured, type, value, traceback are None.
ceback) If an error occured, they will contain information about the class of the exception, the exception
object and a traceback object, respectively. If the exception is handled properly, return True. If it
returns False, the with-block re-raises the exception.
Inheritance / Sub-classing
– We can create a class by inheriting all features from another class.
The “hello” method defined class A:
in class A will be inherited by def hello(self):
class B. print "Hello, I'm A."
class B(A):
The output will be: pass
Hello, I’m A. a = A()
Hello, I’m A. b = B()
a.hello()
b.hello()