Você está na página 1de 6

Numbers

--------
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

Modules and packages


---------
PYTHONPATH can be used to play with the search path
.pth files too
the search path is in sys.path and can be modified at runtime
loaded modules are in sys.modules
from modulename import *|name #imports in current namespace and copies all the
non-mutable objects by-value
import happen only once, unless you use 'reload' - reload is a function not a
statement and is not recursive

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 *

To programmatically import a module:


>>> modname = "string"
>>> exec "import " + modname
OR
>>> modname = "string"
>>> string = __import__(modname)

Don't use from in recursive imports


reload may not impact from 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

Classes and OOP


---------
class A(Superclass1,Superclass2):
pass
assigning to an object's attribute always changes that object, and no other
(lookups go through inheritance tree, not assignments)
class assignments are made at the top level of a class def, without any keyword or
'self'
instance variables are assigned in __init__ using self.XXX
to call the superclass' constructor, use the name of the parent.__init__(),
otherwise, the constructor replaces the parent's
instances have a __class__ attribute containing a reference to their class
classes have a __bases__ tuple containing their parents
assigning to an object's attribute always changes that object, and no other
changing a class variable through an instance does not change the class variable,
but rather assigns a new property to the instance
you cant overload methods in Python, the last definition will be the one used if
you do so
you can use built-in getattr to get an attribute from an object, and you can use
apply to call it

you can mangle names by prepending __ to their names. But it prevents children
from accessing the variable too (multiple inheritance SOL).

__new__ ?
__metaclass__ ?

new style classes inherit frmo built-ins or 'object':


class newstyle(object): ...normal code...
new style classes do a breadth-first search on attribute names instead of a depth
first search for classic classes.
You can of course reassign attributes explicitly to avoid conflicts
new style classes can have __slots__ attribute that lists all the possible
attributes of the class
class limiter(object):
__slots__ = ['age', 'name', 'job']
in new style, you can also use the built-in property to create accessors a la Ruby
new style classes can overload __getattribute__ which intercepts ALL attribute
references
does __getattr__ intercept all refs?

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

Use __iter__ like this:


class Squares: def __init__(self, start, stop):
self.value = start - 1
self.stop = stop
def __iter__(self): # Get iterator object
return self
def next(self): # on each for iteration.
if self.value == self.stop:
raise StopIteration
self.value += 1
return self.value ** 2
#prints out all the squares: 1 4 9 16..

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:

def func(): pass


func = f1(arg)(f2(func))

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 **

default argument are kept and reused between function calls

if you assign to a global var in a function, the variable will be local everywhere
within the function (sic)

Only 0, empty built-ins, False and None are false

Dictionaries can't have lists as keys (keys need to be hashable)

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]]

swap without a tmp var: nudge, wink = wink, nudge

for most for loops, you can append an else block that is executed unless the loop
ended with a break

default argument are kept and reused between function calls

if you assign to a global var in a function, the variable will be local everywhere
within the function (sic)

Only 0, empty built-ins, False and None are false


Dictionaries can't have lists as keys (keys need to be hashable)

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]]

swap without a tmp var: nudge, wink = wink, nudge

for most for loops, you can append an else block that is executed unless the loop
ended with a break