chapter6:python 抽象

来源:互联网 发布:淘宝买亚马逊礼品卡 编辑:程序博客网 时间:2024/06/05 01:10

1 Fibonacci 斐波那契序列 & callable() & __doc__ & help()

#note:如果使用raw_input,则返回的是plain string,需要进行int转换def fib():    num = input('how many numbers you want to get? ')    fibs = [0,1]    for i in range(num-2):        fibs.append(fibs[-2]+fibs[-1])    return fibsprint fib()x = 1print callable(x)   #Falseprint callable(fib) #True 3.0 print hasattr(fib,__call__)def fdocstring(self):    'this is a example for documenting function - docstring'    passprint fdocstring.__doc__help(fib)print fib.__doc__

2没有return或者return没有数据,的函数,实际返回为None

# return nothing (default None)def notReal():    print 'return nothing'    return    print 'not show'print '1----------'notReal()   # return nothingprint '2----------'print notReal() # return nothing None

3参数

传入值若是seq,dict等object,则传入为地址,可以对实参进行修改

s = [1,2,3]def f1(string):    s [0] = 10    string.append(4)f1(s)print s

4example p145

5指定参数名称,调用函数 & 一次传多个参数 *  **

def f2(p1,p2):    print p1,p2f2(p2='2',p1='1') #1 2
def muti1(*i):    print imuti1(1)    #(1,)muti1(1,2,3)#(1, 2, 3)def muti2(*i,**j): #cannot have two **j, **j dict    print i    print jmuti2(1,2,3,name='lili',no=2)(1,2,3){'name':'lili','no':2}def add(x,y): return x+yp = (1,2)print add(*p) #3def with_stars(**p):    print '---', p['name'],p['no'] p = {'name':'lili','no':1}with_stars(**p) # --- lili 1

6 vars(),返回dictionary

x = 1scope = vars()print scope[‘x’] #1

7 global(),全局变量

x = 100def change():    x = 50    y = 60    print 'change() x = ',x    print 'change() global()[x]',globals()['x'] # 100,show global one    global y   #chang to global,can show outside of this func    y = y+100change()print y

8 NESTED SCOPES,嵌套调用

def out(i):    def inter(j):        def inter1(k):            print('----1')            return i*j*k        print('----2')        return inter1    print('----3')    return interprint out(2)(4)(3) # ---- 3 2 1 24

9 递归

# -- Factorialdef factorial(n):    result = n    for i in range(1,n):        result *= i    return resultprint factorial(1)def factorial1(n):    if n==1:        return 1    else:        return n*factorial1(n-1)print factorial1(2)# -- powerdef power(x,n):    if n == 0:        return 1    result = 1    for i in range(n): #range(3)1,2,3;range(1,3)1,2        result *=x    return resultprint '---',power(2,3)def power1(x,n):    if n==0:        return 1    else:        return x*power(x,n-1)print power1(2,3)

example p161

11 Functional programming

# -- map# pass all the elements of a sequence through a given functionprint map(str,range(10))value={'01':'lili','02':'lucy'}value1=[1,2,3]print map(str,value)    #['02', '01']print map(str,value1)   #['1', '2', '3']# -- filter# to filter out items based on a Boolean functiondef func(x):    if x >=0: return True    if x<0 : return Falseseq=[-1,0,2,3,-2]print filter(func,seq) #seq make func return ture; # -- lambda# for define simple function,primarily used with map/filter and reduceprint filter(lambda x:x>=0,seq)# -- reducenum = [1,2,3,4]num1 = [1]print reduce(lambda x,y:x+y,num)print reduce(lambda x,y:x+y,num1)