Escolar Documentos
Profissional Documentos
Cultura Documentos
--------
integers are represented as longs and can be as wide as we need 'em to be
// is a flooring division
/ floors for 2 integers only, otherwise the result is a float (in python 2.5)
Lambda
--------
no statements, just expressions
is a closure, access to all variables from context within which it is created
Strings
--------
'lite"ral'
"liter'al"
u'unicode string'
u"unicode string"
r'raw one'
r"raw too"
no difference between ' and "
You can use sprintf style strings : "\u%0.4i" % num
Files
---------
use the built-in open('file','mode')
modes (a 'b' can be added for binary mode on Windows):
r
rU
r+
w
a
import dir1.dir2.file #package import (init files are read from first to last)
dir1
__init__
dir2
__init__
file
you can prepend top level attributes with a _ to prevent them from being imported
by a import * mod
alternatively, __all__ can also be a list containing the attributes to be imported
by an import *
Buil-in functions
---------
map (like blocks)
>>> map((lambda x: x + 3), counters) # Function expression
[4, 5, 6, 7]
or
>>> map(pow, [1, 2, 3], [2, 3, 4]) # 1**2, 2**3, 3**4
[1, 8, 81]
reduce (like inject)
>>> reduce((lambda x, y: x + y), [1, 2, 3, 4])
10
filter (like reject)
>>> filter((lambda x: x > 0), range(-5, 5))
[1, 2, 3, 4]
iter(list|dic) #returns an iterator on the argument
you can mangle names by prepending __ to their names. But it prevents children
from accessing the variable too (multiple inheritance SOL).
__new__ ?
__metaclass__ ?
Python did not have class methods or static methods before 2.2.
Now you can call the builtin staticmethod or classmethod like this:
class Multi:
def imeth(self, x): # Normal instance method
print self, x
def smeth(x): # Static: no instance passed
print x
def cmeth(cls, x): # Class: gets class, not instance
print cls, x
smeth = staticmethod(smeth) # Make smeth a static method.
cmeth = classmethod(cmeth) # Make cmeth a class method.
You redefine the name to a static/class method..
Static methods do not take a magic first parameter, class methods take the class
object as their first parameter
Method
Overloads
Called for
__init__
Constructor
Object creation: Class( )
__del__
Destructor
Object reclamation
__add__
Operator '+'
X + Y, X += Y
__or__
Operator '|' (bitwise or)
X | Y, X |= Y
__repr__,__str__
Printing, conversions
print X, `X`, str(X)
__call__
Function calls
X( )
__getattr__
Qualification
X.undefined
__setattr__
Attribute assignment
X.any = value
__getitem__
Indexing
X[key], for loops, in tests
__setitem__
Index assignment
X[key] = value
__len__
Length
len(X), truth tests
__cmp__
Comparison
X == Y, X < Y
__lt__
Specific comparison
X < Y (or else __cmp__)
__eq__
Specific comparison
X == Y (or else __cmp__)
__radd__
Right-side operator '+'
Noninstance + X
__iadd__
In-place (augmented) addition
X += Y (or else __add__)
__iter__
Iteration contexts
for loops,in tests, others
Decorators
---------
on decorators:
A function definition may be wrapped by one or more decorator expressions.
Decorator expressions are evaluated when the function is defined, in the scope
that contains the function definition. The result must be a callable, which is
invoked with the function object as the only argument. The returned value is bound
to the function name instead of the function object. Multiple decorators are
applied in nested fashion. For example, the following code:
@f1(arg)
@f2
def func(): pass
is equivalent to:
Exceptions
---------
inherit from Exception and override __repr__ to provide a meaningful string for
exceptions classes
raise string # Matches except with same string object raise string,
data # Pass optional extra data (default=None).
raise instance # Same as: raise instance.__class__ instance.
raise class, instance # Matches except with this class or its superclass
raise # Reraise the current exception
use that form if you need the exception object in except block
except Exception, exc:
print exc.message
Notes
---------
you can curry (or uncurry?) arguments with the * marker, and kwargs with **
if you assign to a global var in a function, the variable will be local everywhere
within the function (sic)
list tricks:
>>> L = [4, 5, 6]
>>> X = L * 4 # Like [4, 5, 6] + [4, 5, 6] + ...
>>> Y = [L] * 4 # [L] + [L] + ... = [L, L,...]
>>> X
[4, 5, 6, 4, 5, 6, 4, 5, 6, 4, 5, 6]
>>> Y
[[4, 5, 6], [4, 5, 6], [4, 5, 6], [4, 5, 6]]
#Because L was nested in the second repetition, Y winds up embedding references
back to the original list assigned to L, and is open to the same sorts of side
effects noted in the last section:
>>> L[1] = 0 # Impacts Y but not X
>>> X
[4, 5, 6, 4, 5, 6, 4, 5, 6, 4, 5, 6]
>>> Y
[[4, 0, 6], [4, 0, 6], [4, 0, 6], [4, 0, 6]]
for most for loops, you can append an else block that is executed unless the loop
ended with a break
if you assign to a global var in a function, the variable will be local everywhere
within the function (sic)
list gotcha:
>>> L = [4, 5, 6]
>>> X = L * 4 # Like [4, 5, 6] + [4, 5, 6] + ...
>>> Y = [L] * 4 # [L] + [L] + ... = [L, L,...]
>>> X
[4, 5, 6, 4, 5, 6, 4, 5, 6, 4, 5, 6]
>>> Y
[[4, 5, 6], [4, 5, 6], [4, 5, 6], [4, 5, 6]]
#Because L was nested in the second repetition, Y winds up embedding references
back to the original list assigned to L, and is open to the same sorts of side
effects noted in the last section:
>>> L[1] = 0 # Impacts Y but not X
>>> X
[4, 5, 6, 4, 5, 6, 4, 5, 6, 4, 5, 6]
>>> Y
[[4, 0, 6], [4, 0, 6], [4, 0, 6], [4, 0, 6]]
for most for loops, you can append an else block that is executed unless the loop
ended with a break