#创建并测试一个函数,然后读取它的__doc__属性,再检查类型
"""
def factorial(n):
'''returns n!'''
return 1 if n<2 else n*factorial(n-1)
print(factorial(42)) #结果是42*41*40*...*1----->42的阶乘
print(factorial.__doc__)#读取函数__doc__属性
print(type(factorial))
#通过别的名称使用函数,再把函数作为参数传递
fact=factorial #函数可以作为对象与变量进行绑定
print(fact)
print(fact(5))
print(map(factorial,range(11))) #map函数的用法
print(list(map(factorial,range(11))))#生成列表
"""
'''
#高阶函数
#定义:接受函数作为参数,或者把函数作为结果返回的函数是高阶函数
#根据单词长度给一个列表排序
fruits=['straeberry','fig','apple','cherry','raspberry'
'banana']
print(sorted(fruits,key=len))
#说明 任何单参数函数都能作为key参数的值
#根据反向拼写给一个单词列表排序
def reverse(word):
return word[::-1] #反向切片 注意单词没有变 只是将反向切片作为排序的依据
print(sorted(fruits,key=reverse))
'''
#如果想使用不定量的参数调用函数,可以编写func(*arge,**keywords)
"""
def factorial(n):
'''returns n!'''
return 1 if n<2 else n*factorial(n-1)
fact=factorial
#计算阶乘列表:map 和 filter与列表推导比较
print(map(fact,range(6)))
print([fact(n) for n in range(6)])
print(list(map(fact,filter(lambda n:n%2,range(6)))))
#使用map和filter计算直到5!的奇数阶乘列表
print([fact(n) for n in range(6) if n%2])
#列表推导式避免使用lambda表达式
"""
"""
#匿名函数
#lambda关键字在python表达式内创建匿名函数
#在参数列表中最适合使用匿名列表
fruits=['straeberry','fig','apple','cherry','raspberry'
'banana']
print(sorted(fruits,key=lambda word:word[::-1]))
#python中除了高阶函数之外 很少用lambda函数,非平凡的lambda表达式
# 要么难以阅读,要么无法写出
"""
"""
#可调用对象
#python中有各种各样可调用的类型,因此判断对象是否可调用,最安全的方法是
# 使用内置函数callable()函数
print(abs,str,13)
print([callable(obj) for obj in (abs,str,13)])
#[True,True,False]
"""
#用户定义可调用函数类型
#不仅python函数是真正的对象,任何python对象都可以表现的像函数,为此
#只需要实现实例方法__call_
"""_
import random
class BingoCage:
def __init__(self,items):
self.__items=list(items)
random.shuffle(self.__items)
def pick(self):
try:
return self.__items.pop()
except IndexError:
raise LookupError('pick from empty BingoCage')
def __call__(self):
return self.pick()
bingo=BingoCage(range(3))
print(bingo.pick())
print(bingo())
"""
#从定位参数到仅限关键字参数
"""
def tag(name,*content,cls=None,**attrs):
'''生成一个或多个HTML标签'''
if cls is not None:
attrs['class']=cls
if attrs:
attr_str=''.join('%s="%s"'%(attr,Value) for attr
,Value in sorted(attrs.items()))
else:
attr_str=""
if content:
return "\n".join('<%s%s>%s</%s>'%
(name,attr_str,c,name)for c in content)
else:
return '<%s%s />'%(name,attr_str)
print(tag('br'))
print(tag('p','hello'))
print(tag('p','hello','world'))
print(tag('p',"hello",id=33))
print(tag('p',"hello",'world',cls='sidebar'))
print(tag(content='testing',name='img'))
>>><br />
>>><p>hello</p>
>>><p>hello</p>
>>><p>world</p>
>>><pid="33">hello</p>
>>><pclass="sidebar">hello</p>
>>><pclass="sidebar">world</p>
>>><imgcontent="testing" />
"""
#装饰器基础知识
#装饰器是可调用的对象,其参数是另一个函数.装饰器可能会处理被装饰的函数
#然后把它返回,或者将其替换成另一个函数或可调用对象
#装饰器通常把函数替换成另一个函数
# def deco(func):
# def inner():
# print('running inner()')
# return inner
# @deco
# def target():
# print('running target()')
# target() #返回值 running inner()
# 闭包
#示例 计算不断增加的系列值的均值
# 方法一 构造类
"""
class Averager():
def __init__(self):
self.series=[]
def __call__(self,new_value):
self.series.append(new_value)
total=sum(self.series)
return total/len(self.series)
ave=Averager()
print(ave(10)) #10
print(ave(11)) #10.5
print(ave(12)) #11.0
"""
#方法2 闭包 高阶函数
"""
def make_averager():
series=[]
def averager(new_value):
series.append(new_value)
total=sum(series)
return total/len(series)
return averager
ave=make_averager()
print(ave(10)) #10
print(ave(11)) #10.5
print(ave(12)) #11.0
"""
"""
def factorial(n):
'''returns n!'''
return 1 if n<2 else n*factorial(n-1)
print(factorial(42)) #结果是42*41*40*...*1----->42的阶乘
print(factorial.__doc__)#读取函数__doc__属性
print(type(factorial))
#通过别的名称使用函数,再把函数作为参数传递
fact=factorial #函数可以作为对象与变量进行绑定
print(fact)
print(fact(5))
print(map(factorial,range(11))) #map函数的用法
print(list(map(factorial,range(11))))#生成列表
"""
'''
#高阶函数
#定义:接受函数作为参数,或者把函数作为结果返回的函数是高阶函数
#根据单词长度给一个列表排序
fruits=['straeberry','fig','apple','cherry','raspberry'
'banana']
print(sorted(fruits,key=len))
#说明 任何单参数函数都能作为key参数的值
#根据反向拼写给一个单词列表排序
def reverse(word):
return word[::-1] #反向切片 注意单词没有变 只是将反向切片作为排序的依据
print(sorted(fruits,key=reverse))
'''
#如果想使用不定量的参数调用函数,可以编写func(*arge,**keywords)
"""
def factorial(n):
'''returns n!'''
return 1 if n<2 else n*factorial(n-1)
fact=factorial
#计算阶乘列表:map 和 filter与列表推导比较
print(map(fact,range(6)))
print([fact(n) for n in range(6)])
print(list(map(fact,filter(lambda n:n%2,range(6)))))
#使用map和filter计算直到5!的奇数阶乘列表
print([fact(n) for n in range(6) if n%2])
#列表推导式避免使用lambda表达式
"""
"""
#匿名函数
#lambda关键字在python表达式内创建匿名函数
#在参数列表中最适合使用匿名列表
fruits=['straeberry','fig','apple','cherry','raspberry'
'banana']
print(sorted(fruits,key=lambda word:word[::-1]))
#python中除了高阶函数之外 很少用lambda函数,非平凡的lambda表达式
# 要么难以阅读,要么无法写出
"""
"""
#可调用对象
#python中有各种各样可调用的类型,因此判断对象是否可调用,最安全的方法是
# 使用内置函数callable()函数
print(abs,str,13)
print([callable(obj) for obj in (abs,str,13)])
#[True,True,False]
"""
#用户定义可调用函数类型
#不仅python函数是真正的对象,任何python对象都可以表现的像函数,为此
#只需要实现实例方法__call_
"""_
import random
class BingoCage:
def __init__(self,items):
self.__items=list(items)
random.shuffle(self.__items)
def pick(self):
try:
return self.__items.pop()
except IndexError:
raise LookupError('pick from empty BingoCage')
def __call__(self):
return self.pick()
bingo=BingoCage(range(3))
print(bingo.pick())
print(bingo())
"""
#从定位参数到仅限关键字参数
"""
def tag(name,*content,cls=None,**attrs):
'''生成一个或多个HTML标签'''
if cls is not None:
attrs['class']=cls
if attrs:
attr_str=''.join('%s="%s"'%(attr,Value) for attr
,Value in sorted(attrs.items()))
else:
attr_str=""
if content:
return "\n".join('<%s%s>%s</%s>'%
(name,attr_str,c,name)for c in content)
else:
return '<%s%s />'%(name,attr_str)
print(tag('br'))
print(tag('p','hello'))
print(tag('p','hello','world'))
print(tag('p',"hello",id=33))
print(tag('p',"hello",'world',cls='sidebar'))
print(tag(content='testing',name='img'))
>>><br />
>>><p>hello</p>
>>><p>hello</p>
>>><p>world</p>
>>><pid="33">hello</p>
>>><pclass="sidebar">hello</p>
>>><pclass="sidebar">world</p>
>>><imgcontent="testing" />
"""
#装饰器基础知识
#装饰器是可调用的对象,其参数是另一个函数.装饰器可能会处理被装饰的函数
#然后把它返回,或者将其替换成另一个函数或可调用对象
#装饰器通常把函数替换成另一个函数
# def deco(func):
# def inner():
# print('running inner()')
# return inner
# @deco
# def target():
# print('running target()')
# target() #返回值 running inner()
# 闭包
#示例 计算不断增加的系列值的均值
# 方法一 构造类
"""
class Averager():
def __init__(self):
self.series=[]
def __call__(self,new_value):
self.series.append(new_value)
total=sum(self.series)
return total/len(self.series)
ave=Averager()
print(ave(10)) #10
print(ave(11)) #10.5
print(ave(12)) #11.0
"""
#方法2 闭包 高阶函数
"""
def make_averager():
series=[]
def averager(new_value):
series.append(new_value)
total=sum(series)
return total/len(series)
return averager
ave=make_averager()
print(ave(10)) #10
print(ave(11)) #10.5
print(ave(12)) #11.0
"""