本文主要是介绍chapter6:python 抽象,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
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 = 1
print callable(x) #False
print 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'returnprint 'not show'
print '1----------'
notReal() # return nothing
print '2----------'
print notReal() # return nothing None
3参数
传入值若是seq,dict等object,则传入为地址,可以对实参进行修改
s = [1,2,3]
def f1(string):s [0] = 10string.append(4)
f1(s)
print s
4example p145
5指定参数名称,调用函数 & 一次传多个参数 * **
def f2(p1,p2):print p1,p2
f2(p2='2',p1='1') #1 2
def muti1(*i):print i
muti1(1) #(1,)
muti1(1,2,3)#(1, 2, 3)def muti2(*i,**j): #cannot have two **j, **j dictprint iprint j
muti2(1,2,3,name='lili',no=2)
(1,2,3)
{'name':'lili','no':2}def add(x,y): return x+y
p = (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 = 1
scope = vars()
print scope[‘x’] #1
7 global(),全局变量
x = 100
def change():x = 50y = 60print 'change() x = ',xprint 'change() global()[x]',globals()['x'] # 100,show global oneglobal y #chang to global,can show outside of this funcy = y+100
change()
print y
8 NESTED SCOPES,嵌套调用
def out(i):def inter(j):def inter1(k):print('----1')return i*j*kprint('----2')return inter1print('----3')return inter
print out(2)(4)(3) # ---- 3 2 1 24
9 递归
# -- Factorial
def factorial(n):result = nfor i in range(1,n):result *= ireturn result
print factorial(1)def factorial1(n):if n==1:return 1else:return n*factorial1(n-1)
print factorial1(2)# -- power
def power(x,n):if n == 0:return 1result = 1for i in range(n): #range(3)1,2,3;range(1,3)1,2result *=xreturn result
print '---',power(2,3)def power1(x,n):if n==0:return 1else: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 function
print 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 function
def func(x):if x >=0: return Trueif x<0 : return False
seq=[-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 reduce
print filter(lambda x:x>=0,seq)
# -- reduce
num = [1,2,3,4]
num1 = [1]
print reduce(lambda x,y:x+y,num)
print reduce(lambda x,y:x+y,num1)
这篇关于chapter6:python 抽象的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!