内容简介:新手Python第三天(函数)
Python 函数的创建
def func2(): print('haha') # 函数的返回值 # 函数的返回值,没有定义返回None, # 有一个返回值返回这个object(可以返回一个函数对象), # 有多个则是返回一个元组 return 0 View Code
Python 函数的调用
func2()
Python 函数的参数
def func3(x,y,z=5,*args,**kwargs): print(x) print(y) print(z) func3(1,2,3) #实际参数(实参):1,2,,3 #形式参数(形参):x,y,z #默认参数:z=5,(非必须传递) View Code
def func3(x,y,z=5,*args,**kwargs): print(x) print(y) print(z) #位置参数的传递,位置的特性:需要一一对应 func3(1,2,3) #关键字参数的传递,关键字的特性:不需要一一对应 func3(x=1,y=2,z=3) #非固定参数:*args,**kwargs #*args接收多余的位置参数的值,以元组形式 #**kwargs接收多余的关键字参数的值,以字典的方式 #混合参数的传递,特性:位置参数要在关键字参数前面,继承了位置和关键字的特性 func3(1,y=2,z=3) View Code
Python 全局和局部变量
def test(): name='xiaoming'#这是一个局部变量 global name #定义一个全局变量 View Code
Python 函数的递归
递归的三大特性:1.必须要有明确的结束条件,2.每次问题的规模要有所减少,3.递归的效率不高
def calc(n): print(n) if n>0: return calc(int(n/2)) calc(10) View Code
Python 高阶函数
高阶函数分为二种(函数即变量):1.一个函数当参数传递个另一个函数,return返回一个函数的内存地址
#函数当参数传递 def add(a,b,i): res=i(a)+i(b) print(res) add(1.222,2.111,int) #函数当返回值返回 def func4(): print('this is func4') return func5 def func5(): print('this is func5') func5=func4() func5() View Code
Python 函数的嵌套
#函数的嵌套 def func6(): print('this is func6') def func7(): print('this is func7') func7() func6() View Code
Python 装饰器
装饰器的条件:高阶函数+函数的嵌套
def logger(funcTest): #把源代码的内存地址传递给装饰器 def waps(*args,**kwargs): #封装内部装饰器 print('befor') #装饰的内容 res=funcTest(*args,**kwargs)#调用源代码 print('after') return res #返回funcTest的结果 return waps #返回封装的装饰器 @logger #funcTest=logger(funcTest) #被装饰函数的源代码 def funcTest(x): print('this is test file',x) return x #funcTest=logger(funcTest) #logger返回的是waps的内存地址, x=funcTest(x=1) #实际调用的是上方的waps,通过内部的waps调用的funcTest print(x) View Code
Python 三层装饰器
def auth(auth_type): #第三层加入装饰器参数 def out(func): def wrapper(*args,**kwargs): if auth_type=='localhost': if local_login(): print('登入成功') return func(*args,**kwargs) else: print('登入失败') elif auth_type=='file': if file_login(): pass #文件接口登入 else: print('没有这个登入接口') return wrapper return out @auth(auth_type='localhost') def index(): print('welcome to index page') index() View Code
以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,也希望大家多多支持 码农网
猜你喜欢:本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们。
Operating System Algorithms
Nathan Adams、Elisha Chirchir / CreateSpace Independent Publishing Platform / 2017-4-21 / USD 39.15
Operating System Algorithms will walk you through in depth examples of algorithms that you would find in an operating system. Selected algorithms include process and disk scheduling.一起来看看 《Operating System Algorithms》 这本书的介绍吧!
在线进制转换器
各进制数互转换器
HEX CMYK 转换工具
HEX CMYK 互转工具