判断用户是不是root用户,root用户可添加删除:
def pd(fun): def wrapper(name): if name == 'root': fun(name) else: print('不是root用户') return wrapper @pd def add_student(name): print ('添加学生信息...') @pd def del_student(name): print('删除学生信息...') add_student('root') del_student('root')
装饰器实现一个函数计时器,可计算出函数的运算时间
提示四个包:
import time
import random
import string
import functools
import time import random import string import functools #问题1:被装饰的函数有返回值 #问题2:如何保留被装饰函数的函数名和帮助信息文档 li = [random.choice(string.ascii_letters) for i in range(100)] # print(li) def timeit(fun): @functools.wraps(fun) #保留被装饰函数的函数名和帮助信息文档否则默认返回wrapper函数的帮助信息 def wrapper(*args,**kwargs): """这是一个wrapper函数""" start_time = time.time() res = fun(*args,**kwargs) end_time = time.time() print('运行时间为:%.6f' %(end_time - start_time)) return res #有返回值返回,因为con_add()和join_add()函数没有返回值,可注释。 return wrapper @timeit def con_add(): """这是for循环""" s = '' for i in li: s += (i + ',') print(s) @timeit def join_add(): """这是join方法""" print(','.join(li)) @timeit def fun_list(n): """这是fun_list函数""" return [i * 2 for i in range(n)] @timeit def fun_map(n): """这是fun_map函数""" return list(map(lambda x:x*2,range(n))) con_add() # join_add() print(con_add.__doc__) print(con_add.__name__) # print(join_add.__doc__) # print(join_add.__name__) print(fun_list(5000)) print(fun_map(5000))
请写一个包含10个线程的程序,主线程必须等待每一个子线程执行完成之后才结束执行,每一个子线程执行的时候都需要打印当前线程名、当前活跃线程数量;
from threading import Thread, currentThread, activeCount import time def task(n): print('线程名:%s----%s' % (currentThread().name, n)) time.sleep(1) print('数量:%s' % activeCount()) if __name__ == "__main__": t_li = [] for i in range(10): t = Thread(target=task, args=(i,)) t.start() t_li.append(t) for t in t_li: t.join() print('主,end----')
写一个程序,包含十个线程,同时只能有五个子线程并行执行;
from threading import Thread, Semaphore, currentThread import time def task(n): sm.acquire() print('%s---' % n, currentThread().name) time.sleep(1) print('end----') sm.release() if __name__ == '__main__': sm = Semaphore(5) for i in range(10): t = Thread(target=task, args=(i,)) t.start()
写一个程序,包含十个线程,子线程必须等待主线程sleep 10秒钟之后才执行,并打印当前时间;
from threading import Thread, Event import time import datetime def task(): # while not event.is_set(): # print('...') print('...') event.wait(10) print('time:', datetime.datetime.now()) if __name__ == '__main__': event = Event() for i in range(10): t = Thread(target=task) t.start() time.sleep(10) event.set()