函数和过程
1.面向对象:类 class
2.面向过程:过程 def
3.函数式编程:函数 def
# 函数,有返回值
def func1():
print("func 1")
return 0
# 过程,没有返回值
def func2():
print("func 2")
x = func1()
y = func2()
print("func1 return is %s" % x)
print("func2 return is %s" % y)
"""OUTPUT
func 1
func 2
func1 return is 0
func2 return is None
"""
函数的好处
1、代码复用
2、保持一致性
3、可扩展
举例:打印日志的功能
import time
def printlog():
time_format = "%Y-%m-%d %X"
current_time = time.strftime(time_format)
with open("logger.log", "a") as f:
f.write("%s\n" % current_time)
def tes1():
print("test1")
printlog()
def tes2():
print("test2")
printlog()
def tes3():
print("test3")
printlog()
tes1()
tes2()
tes3()
"""OUTPUT
test1
test2
test3
"""
函数的返回值
1.返回为0个参数,None
2.返回为1个参数,object
3.返回为多个参数,tuple
def foo1():
print("hello, world")
def foo2():
print("hello, world")
return 0
def foo3():
print("hello, world")
return 1, [1,2], {"key": "value"}, "string"
x = foo1()
y = foo2()
z = foo3()
print(x)
print(y)
print(z)
"""OUTPUT:
hello, world
hello, world
hello, world
None
0
(1, [1, 2], {'key': 'value'}, 'string')
"""
函数参数
位置参数:positional argument
关键字参数:keyword arg
默认参数
def foo(x, y=2):
print("x=", x, "y=", y)
foo(1, 2) # 位置参数,实参与形参对应
foo(x=2, y=1) # 关键字参数,实参与形参位置无关
foo(3, y=4) # 关键字参数要放到最后
foo(3) #默认参数,可以不传参
"""OUTPUT
x= 1 y= 2
x= 2 y= 1
x= 3 y= 4
x= 3 y= 2
"""
位置参数
任意多个参数,转为元组形式
def foo(*args): # 接收位置参数
print(args)
foo(1,2,3,4,5,6) # *表达式可以传任意多个参数
# ->(1, 2, 3, 4, 5, 6)
foo([1,2,3,4,5,6,7,9])
# ->([1, 2, 3, 4, 5, 6, 7, 9],)
foo(*[1,2,3,4,5,6,7,9])
# ->(1, 2, 3, 4, 5, 6, 7, 9)
关键字参数
参数组:多个关键字参数,转为字典形式
def foo(**kwargs): # 接收关键字参数
print(kwargs)
print(kwargs["name"])
foo(name="Tom", age=8, sex="man")
# ->{'name': 'Tom', 'sex': 'man', 'age': 8}
foo(**{'name': 'Tom', 'sex': 'man', 'age': 8})
# ->{'age': 8, 'name': 'Tom', 'sex': 'man'}
多种参数混合
def foo(name, age=8, *args, **kwargs):
print(name)
print(age)
print(args)
print(kwargs)
foo("Tom", 78,"heh",habyy="swimming")
"""OUTPUT
Tom
78
('heh',)
{'habyy': 'swimming'}
"""