python路7__面向对象编程
1,def 定义函数
def test1(): print ('in the test1') def test2(): print ('in the test2') return 2 def test3(): print ('in the test3') return 1,'hello',[1,2,3],{'name':'Tom'} x = test1() y = test2() z = test3() print (type(x),x) print (type(y),y) print (type(z),z)
运行结果:
root@pythonserver:/python_shell# python3 code_fileoperator.py
in the test1
in the test2
in the test3
< class 'NoneType'> None
< class 'int'> 2
< class 'tuple'> (1, 'hello', [1, 2, 3], {'name': 'Tom'})
root@pythonserver:/python_shell#
2,形参、实参
(1)位置参数和关键参数
def test(x,y): print(x,y) test(1,2) #位置参数:与形参一一对应 test(x=1,y=2) #关键参数:与形参顺序无关 test(3,y=2) #位置、关键参数混合:注意要一一对应,关键参数不能在位置参数的 #前面 def test1(x,y=2): #默认参数:调用函数的时候,默认参数一定会传递,用于给赋予默认值 print ('test1',x,y) test1(1) test1(1,y=3)
(2)*args
*args:可以接受多个位置参数,转换成元组的方式,然后将他们放入args元组里面,args是所有实参组成的元组
def test(*args): print (args)
print (*args) test(1,2,3,4,5) test(*[1,2,3,4,5]) #*args = tuple[1,2,3,4,5]
运行结果:root@pythonserver:/python_shell# python3 code_fileoperator.py
(1, 2, 3, 4, 5)
1 2 3 4 5
(1, 2, 3, 4, 5)
1 2 3 4 5
(3)**kwargs
**kwargs:接受字典形式的实参,把关键字转化成字典的方式
kwargs是一个字典,如果没有实参传递进来字典为空
def test(**kwargs): print (kwargs) print (kwargs['name']) print (kwargs['age']) print (kwargs['sex']) test(name = 'TangSehng',age = 18,sex = 'Men') test(**{'name':'TangSehng','age':18,'sex':'Men'}) 运行结果: root@pythonserver://python_shell# python3 code_fileoperator.py {'age': 18, 'sex': 'Men', 'name': 'TangSehng'} TangSehng 18 Men {'age': 18, 'sex': 'Men', 'name': 'TangSehng'} TangSehng 18 Men
(4)形参混合使用
实参只有两种形式:位置参数和关键参数
三个原则:1,形参实参一一对应
2,关键参数不能有重复
3,关键参数不能在位置参数前面(记住这个,不变应万变)
#错误实例; def test1(name,age=18,*args,**kwargs): print (name) print (age) print (args) print (kwargs) test1('Tobet',age=34,1,2,3,4,sex='men',node=13) #位置参数1,2,3,4不能在关键字参数后面
运行结果:root@pythonserver://python_shell# python3 code_fileoperator.py
File "code_fileoperator.py", line 14
test1('Tobet',age=34,(1,2,3,4),sex='men',node=13)
^
SyntaxError: positional argument follows keyword argument
#正确实例; def test1(name,*args,age=18,**kwargs): print (name) print (age) print (args) print (kwargs) test1('Tobet',1,2,3,4,age=34,sex='men',node=13) 运行结果: root@pythonserver://python_shell# python3 code_fileoperator.py Tobet 34 (1, 2, 3, 4) {'sex': 'men', 'node': 13}
#简化使用 def test1(*args,**kwargs): a,b,c,d = args print (a,b,c,d) print (args) print (kwargs) print(kwargs['age']) test1(1,2,3,4,age=18,sex='men') 运行结果: root@pythonserver://python_shell# python3 code_fileoperator.py 1 2 3 4 (1, 2, 3, 4) {'sex': 'men', 'age': 18} 18

浙公网安备 33010602011771号