偶然想到的小技巧

'''
交互中对传入函数的参数的数目进行检测
'''
def func(a,b,c):
print(a,b,c) s=input(">>>>:")
s=s.split()
t=tuple(s)
try: #Python本身会检测输入函数的参数数目是否对应,
func(*t) #*[元组]的方式传参数 #如果不对应,会报出TypeError,
except TypeError: # 所以可以捕获typeerror来方便的进行参数数目的检测
print("参数错误") #**kwargs 的方式传参也可以
#===================================================================>
# def func(x,y,*args): #args=(3,4,5,6)
# print(x,y)
# print(args)
#
# func(1,2,*(3,4,5,6)) #foo(1,2,3,4,5,6) #这样传参和解开元组后传参效果是一样的
#=====================================================================================>
# def func(x,y,**kwargs): #x=1,y=2,**kwargs=**{'a':1,'b':3,'z':3}
# print(x,y)
# print(kwargs)
#
# func(1,y=2,**{'a':1,'b':3,'z':3}) #func(1,y=2,z=3,b=3,a=1) #这样传参就和解开字典后传参,效果一样
#不加*、**,元组、字典就没有响应的功能,只能传给一个形参
#函数是第一类对象: 指的是函数可以被当做数据传递

# def func():
# print('from func') #可被引用
# f=func #可以当做函数的参数
# def func():
# print('from func')
# def foo(x):
# print(x)
# x() # foo(func) #可以当做函数的返回值
# def foo():
# print('from foo')
# def bar():
# return foo
# f=bar()
# print(f)
# print(foo)
# f() # x=0
# def f1():
# x=1
# def f2():
# # x=2
# print(x)
# return f2
# f=f1()
# print(f)
# f() #可以当做容器类型的元素
# def select():
# print('select function')
#
# func_dic={
# 'select':select,
# }
#
# print(func_dic['select'])
# func_dic['select']()
# #
# def select():
# print('select func')
#
# def delete():
# print('delete func')
#
# def change():
# print('change func')
#
# def add():
# print('add func')
#
#
# while 1:
# cmd=input('>>: ').strip()
# if not cmd:continue
# if cmd == 'select':
# select()
# elif cmd == 'delete':
# delete()
# elif cmd == 'change':
# change()
# elif cmd == 'add':
# add()
# else:
# print('无效的命令') def select(cmd_l):
filename=cmd_l[-1]
pattern=cmd_l[1] with open(filename,'r',encoding='utf-8') as f:
for line in f:
if pattern in line:
print(line) def delete():
print('delete func') def change():
print('change func') def add():
print('add func') def check():
print('check func') func_dic={
'select':select,
'delete':delete,
'change':change,
'add':add,
'check':check,
} while 1:
inp=input('>>: ').strip()
if not inp:continue #如果输入为空则继续 输入自带bool值,如果为空,bool值为FALSE,不空则为True。
cmd_l=inp.split()
# print(cmd_l)
cmd=cmd_l[0]
if cmd in func_dic:
func_dic[cmd](cmd_l)
else:
print('无效的命令')

函数是第一类对象

#有参装饰器,在一般装饰器之外添加针对装饰函数的参数,增加了新参数,所以再加包一层
def deco(auth_type='file'):
def auth(func):
def wrapper(*args,**kwargs):
if auth_type == 'file':
print('文件的认证方式')
elif auth_type == 'ldap':
print('ldap认证方式')
elif auth_type == 'mysql':
print('mysql认证方式')
else:
print('不知到的认证方式')
return wrapper
return auth @deco(auth_type='abc') #@auth #index=auth(index)
def index():
print('welecome to index') @deco(auth_type='ldap')
def home(name):
print('welecome %s to home page' %name) index() home('egon')

有参装饰器

#直接使用地址调用函数能够跳过装饰器
with open(r'D:\py\empty\c.txt','r',encoding='utf-8') as f:
print(sum([float(i.split()[1])*int(i.split()[2]) for i in f]))
f.seek(0) #光标初始化
print([item for line in f for item in line.split() if item.isdigit()])
f.seek(0) #光标初始化

列表解析是能够套多层for循环的

def init(func):                   #send必须传值到yield,所以需要先将生成器暂停到一个yield,相当于每次send之前先要初始化一次。如果send的时候不是yield暂停,会报错
def wrapper(*args,**kwargs):
g=func(*args,**kwargs)
next(g)
return g
return wrapper @init
def eater(name):
print('%s ready to eat' %name)
food_list=[]
while True:
food=yield food_list #send传入的值给了yield,赋值给了food,但是执行结束的时候,返回值是food_list,和yield本身传入的值没有关系。
food_list.append(food)
print('%s start to eat %s' %(name,food))

yield生成器

# sleep(secs)    #------------------time.sleep()  I/O阻塞,(类似于input)不占cpu
# 线程推迟指定的时间运行,单位为秒。

sleep(secs)

随机推荐

  1. 第二百七十八节,MySQL数据库-表内容操作

    MySQL数据库-表内容操作 1.表内容增加 insert into 表 (列名,列名...) values (值,值,值...); 添加表内容添加一条数据 insert into 表 (列名,列名. ...

  2. java------HashMap与HashSet的区别

    HashMap和HashSet的区别是Java面试中最常被问到的问题.如果没有涉及到Collection框架以及多线程的面试,可以说是不完整.而Collection框架的问题不涉及到HashSet和H ...

  3. Unity Shaders and Effects Cookbook (3-5) 金属软高光

    书上这一节看得我头昏脑胀,数学渣表示自理不能-- 并且也不了解这个效果的实际意义. 先记录下来,后面真正看懂了再来补充具体理论. 通过一张纹理贴图,定义高光的形状,利用到的纹理贴图有三种 这里并非把纹 ...

  4. hdu 1503:Advanced Fruits(动态规划 DP & 最长公共子序列(LCS)问题升级版)

    Advanced Fruits Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others)T ...

  5. hdu 2809(状压dp)

    题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=2809 思路:简单的状压dp,看代码会更明白. #include<iostream> #in ...

  6. shrink-to-fit(自适应宽度)

    自适应宽度是指当未明白设定容器的宽度(或外边距设为auto)时,在特定的情况下容器的宽度会依据情况自行设定.而设定的结果往往并非我们想要的. W3C规范中描写叙述了几种shrink-to-fit的情况 ...

  7. Deep Learning的基本思想

    假设我们有一个系统S,它有n层(S1,…Sn),它的输入是I,输出是O,形象地表 示为: I =>S1=>S2=>…..=>Sn => O,如果输出O等于输入I,即输入I ...

  8. shell脚本学习总结02--数组

    bash同时支持普通数组个关联数组,普通数组只能使用整数作为数组的索引,关联数组可以使用字符串作为数组的索引. 数组的定义方法: 在单行中使用一列值定义一个数组 [root@new ~]# array ...

  9. measure layout onMeasure() onLayout()

    1.onMeasure() 在这个函数中,ViewGroup会接受childView的请求的大小,然后通过childView的 measure(newWidthMeasureSpec, heightM ...

  10. 部分 II. 保护web篇

    转载:http://www.mossle.com/docs/auth/html/pt02-web.html 部分 II. 保护web篇   2012-12-5 23:42:36 org.springf ...