Oct 5, 2008

Learning python 读书笔记 PART 4

PART FOUR. FUNCTIONS
Chapter 12. Function Basics
calls:  myfunc(argv)
def, return, yield: def adder(a, b=1, *c): return a+b+c[0]
global:  def function(): global x; x = 'new'
lambda:  funcs = [lambda x: x**2, lambda x: x*3]
1. Coding Functions
def is a executable statement which create an object and assigns it to a name
arguments are passed by assignment
global declares module-level variables that are to be assigned
def <name> (arg1, arg2...):
    ...
    return <value>
def can executes at runtime
if test:
    def function():
else:
    def function():
2. Definitions and Calls
Polymorphism in Python: because python is a dynamically typed language, every operation is polymorphic in python
in python, code is not supposed to care about specific data types.

Chapter 13. Scopes and Arguments
1. Scope Rules
Name <--> Namespace
The enclosing module is a global scope
The global scope spans a single file only
Each call to a function is a new local scope
Assigned names are local, unless declared global
All other names are enclosing locals, globals, or built-ins
LEGB: local --> enclosing functions --> global --> built-in
the built-in scope
>>> import __builtin__
>>> dir(__builtin__)
zip <--> import __builtin__,  __builtin__.zip
2. The global Statements
3. Scope and Nested Functions
LEGB: statically nested scope
lambda: an expression that generates a new function to be called later, much like def statement
4. Passing Arguments
immutable arguments <--> C's "by value" mode
mutable arguments <--> C's "by pointer" mode
Avoiding mutable arguments change:
pass a copy or tuple
Simulating output parameters:
>>> def multiple(x,y):
    x = 2
    y = [3,4]  #change local names only
    return x,y #return new values in a tuple(not two values)
>>> x = 1
>>> y = [1,2]
>>> x,y = multiple(x,y)  #assign result to caller's names
>>> x,y
(2, [3, 4])
5. Special Argument Matching Modes
func(value)    : Normal argument: matched by position
func(name=value)    : Keyword argument: matched by name
self documention, more meaningful
def func(name)   
def func(name=value)    : default argument value, if not passed in the call
make some arguments optional
def func(*name)    : Matchs remaining positional args(in a tuple)
>>>def f(*args): print args
def func(**name)    : Matchs remaining keyword args(in a dict)
>>>def f(**args): print args
>>>f(a=1,b=2)
{'a':1, 'b':2}
Argument Matching
rules:
key arguments after non-keyargument
*name after normal argument
**name last
Matching steps:
non-key argus --> key word argus --> extra non-key argus --> extra key argus -->default values

Chapter 14. Advanced Function Topics
1. Anonymous Functions: lambda
lambda expression creates a function to be called later, but returns it instead of assigning it to a name
lambda argu1, argu2, argu3...arguN: expression using argus
lambda bodies are single expression, not a block of statements
example1:
L = [(lambda x: x**1),(lambda x: x**2), (lambda x: x**3)]
for f in L
    print f(2)
print L[0](2)
example2:
key = 'b'
{'a': (lambda f1),
  'b': (lambda f2),
}[b]()
is equivalent to
def f1():...
def f2():...
...
key = ...
{'a':f1, 'b':f2}[key]()
How(not) to obfuscate your python code
((a and b) or c) is roughly equivalent to:
if a: b else: c
(C's a?b:c)
2. Applying Functions to Arguments
The apply built-in
apply(func, argus) == func(argus)
argument list is passed by tuple
if <test>:
    action,args = func1, arguments_a
else
    action,args = func2, arguments_b
...
apply(action,args)
3. Functions Over Sequences
>>> counter = [1,2,3,4]
>>> def func(x): return x + 10
>>> map(func,counter)
[11, 12, 13, 14]
>>>map((lambda x: x + 3), counter)
[3,4,5,6]
map(func,[1,2,3],[4,5,6]) #[func(1,4),func(2,5),func(3,6)]
4. Functional Programing Tools
filter
>>>filter((lambda x: x>0), range(-5,5))
[1,2,3,4]
reduce
>>>reduce((lambda x, y: x+y), [1,2,3,4]) 
10
>>>import operator
>>>reduce(opetator.add, [1,2,3,4])
5. List Comperhensions
[x ** 2 for x in range(10)]
map((lambda x: x ** 2), range(10))
[x for x in range(5) if x%2 == 0]
filter((lambda x: x%2 == 0), range(5))
map((lambda x: x**2), filter((lambda x: x%2 == 0),range(10)))
the genaral structure of list comprehensions
[expression for target1 in sequence 1 [if condition]
                for target2 in sequence 2 [if condition]....
                for targetN in sequence N [if condition]]
list comperhension and map are faster than for loop.
6. Generators and Iterators
Generators yield a value rather than returning one. The yield statment suspends the function and sends a value back to the caller and allow the function to resume from where it left off.
>>> def gensqure(N):
    for i in range(N):
        yield i ** 2
>>>x=gensqure(10)
>>>x.next(), x.next()...
Iterators and built-in type: iter(L)
__iter__ method

0 comments: