偏函数
偏函数就是把以前功能函数的默认参数修改重新成立一个函数
比如:int('1010',base=10)默认是十进制
将其重写为二进制
print(int('10101'))#默认base=10
def int2(str):
return int(str,base=2)
print(int2('10101'))
print(int2('101010101'))
第一个输出的是十进制的结果 第二个是把字符串当作一个二进制来输出其数值 十进制数值。
自动创建偏函数:
我们可以通过functools模块来自动创建函数
import functools
int3=functools.partial(int,base=8)#将最终的函数赋值给int3,将它修改为八进制
print(int3('71230'))
print(int3('10101'))
回调函数
回调函数:当一个函数传递变量解决不了问题的时候,那么只能传递函数来解决问题。
将函数当作参数传递到另外一个函数,从而改变另外一个函数的行为,这个函数就是回调函数。
好处灵活方便 用来实现不同业务的需求。
通过我目前自学知识的了解,回调函数一般运用在python的多线程中 比如向文件中写入东西。
或者在进行操做是 输入的值不同 通过回调函数来达到不同的输出结果 影响之后回调函数的行为。
比如举例 通过回调函数向文件中写入值。
from multiprocessing import Pool
import time
def mycallback(x):
with open('poem.txt', 'a+') as f: #这里是回调函数向文件中写入值
f.writelines(str(x))
def sayHi(num):
return num
if __name__ == '__main__':
e1 = time.time()
pool = Pool()
for i in range(10):
pool.apply_async(sayHi, (i,), callback=mycallback)#池的多线程
pool.close()
pool.join()
e2 = time.time()
print(float(e2 - e1))
举个比较简单的例子 输出hello 输入的参数不同可以得到不同的次数 通过回调函数来实现就是:
def hello(times):
for x in range(times):
print('hello')
def my_callback(times,hello):
return hello(times)
my_callback(10,hello)