#return的三种情况,如果不写,返回None,如果写一个就返回写的那个,如果多个,就放在一个元组里返回,还有如果返回是要给函数没有括号,就返回这个函数。如果有括号,就返回这个函数执行后的结果,然后在返回返回值。
def test1():
print("hello")
def test2():
print("hello")
return test1
def test3():
print("hello")
return 1,"hello",["h","e","l","l","o"],(1,2,3,),{"name":"gongwei"}
def test4():
print("hello")
return test1
def test5():
print("hello")
return test1()
print("1",test1())
print("2",test2())
print("3",test3())
print("4",test4())
print("5",test5())
def test6(x,y):
print(x)
print(y)
test6(y=9,x=8)#关键字参数调用
test6(8,9)#位置参数调用
#test6(x=8,9)#注意着会报错,关键字参数不能写在位置参数前面。因为执行的时候首先要看到位置参数,比如把8传进去,然后才能考虑其他参数情况(注意必须把位置位置参数连续传完,才能传其他形式参数)
test6(8,y=9)
def test7(x,y=2):#默认参数
print(x,y)
test7(2)
def test8(*args):#以*开始后面args可以随意写,表示可以接受多个形参作为输入,结果把这些返回值放在一个元组里面
print(args)
test8(1,2,3,4,5,6)
test8(*[1,2,3,4,5])#[1,2,3,4,5]=args
def test9(*args,**kwargs):#**args把N个关键字参数转换成字典的方式,位置参数不能写在关键字参数之后
print(kwargs)#如果是return,就是把kwargs放在字典里返回
print(args)
test9(9,name="gongwei",age=24,sex="M")
test9(**{"name":"gonwei","age": 8})
代码运行情况:
hello
1 None
hello
2 <function test1 at 0x00000207EB5C3048>
hello
3 (1, 'hello', ['h', 'e', 'l', 'l', 'o'], (1, 2, 3), {'name': 'gongwei'})
hello
4 <function test1 at 0x00000207EB5C3048>
hello
hello
5 None
8
9
8
9
8
9
2 2
(1, 2, 3, 4, 5, 6)
(1, 2, 3, 4, 5)
{'name': 'gongwei', 'age': 24, 'sex': 'M'}
(9,)
{'name': 'gonwei', 'age': 8}
()