- 函数
- 1、语法
- 2、函数的参数
- 3、不定长参数
- 3、参数的解包
- 4、返回值
- 5、函数的帮助文档help()
- 6、作用域
函数
函数是一段可执行的代码,在python中,它也是一种对象,也是一段数据,被保存在内存中,在需要的时候会被取出来执行,多次调用 函数在python中是一等对象 1、对象在运行时创建 2、能赋值给变量或者作为数据结构中的元素 3、能作为参数传递 4、能作为返回值使用
1、语法
def 函数名(形参1,形参2,... ,形参n): 函数体
函数名称命名 规则一般是按照字母+下划线,或者驼峰法则
def sayHello():
print('hello')
print(sayHello) #
print(type(sayHello)) #
# 函数调用
sayHello() # hello
2、函数的参数
形参(形式参数) 实参(实际参数)
def add(a,b):
a += 10
print(a+b)
a = 10
b = 20
add(10,20) # 40
print(a) # 10
函数调用的时候,实际参数的数量和定义的形式参数的数量一致 如果不强调,位置也要一样 位置可以通过名字来强调关键字参数 还可以混用,但是关键字参数一定要放在后面
add(b = 1, a = 2) # 调用的时候,按照参数名去传递 add(b=1,2) # 错误SyntaxError: positional argument follows keyword argument add(2,b=1) # 正确,13 add(2,a=1) # 错误,TypeError: add() got multiple values for argument 'a'
# 函数调用的时候,不会检查传入的参数的类型
add(True,10) # 21
add('a',10) # 报错,TypeError: can only concatenate str (not "int") to str
# 解决办法:参数类型注解(比较麻烦不用掌握)
import inspect
def add(a:int,b:int):
print(a+b)
sig = inspect.signature(add)
params = sig.parameters
print(params,type(params))
for v in params.values():
print(v)
# 和Java一样,参数传递也是值拷贝
def add(a,b):
total = 0
for i in a:
total += i
for i in b:
total += i
print(total)
a = [1,2,3]
b = [4,5]
add(a,b) # 15
def add(a,b):
total = 0
for i in a:
total += i
for i in b:
total += i
print(total)
a.append(4)
b.append(5)
a = [1,2,3]
b = [4,5]
add(a,b) # 15
print(a,b) # [1, 2, 3, 4] [4, 5, 5]
3、不定长参数
# 在元组拆包中可以用*去代表若干剩下的参数
def add(*nums:int):
print(nums,type(nums))
add(1,2,3) # (1, 2, 3)
# 推荐写成下面这样,标记好返回类型
def add(*nums:int) -> int:
total = 0
for i in nums:
total += i
return total
print(add(1,2,3)) # 6
带*号的不定长参数只能有1个,可以和其他的参数混用
Java不定长参数只能防砸最后,python随便,但有规则
def add(a,b,*c):
total=0
total += a*100
total += b*10
for i in c:
total += i
return total
print(add(1,2,3,4,5))
# 如果不定项参数不放在最后,那么必须用关键字参数的方式传递
def fn(*a,b,c):
print(a)
print(b)
print(c)
fn(1,2,3,b=4,c=5)
'''
(1, 2, 3)
4
5
'''
def fn(a,*b,c):
print(a)
print(b)
print(c)
fn(1,2,3,4,c=5)
'''
1
(2, 3, 4)
5
'''
# 第一个参数位置直接使用一个*号,表示必须使用关键字参数传递所有参数
def fn(*,a,b,c):
print(a)
print(b)
print(c)
fn(a=1,b=2,c=3)
'''
1
2
3
'''
fn(1,2,3) # 报错,TypeError: fn() takes 0 positional arguments but 3 were given
fn(1,2,3,a=1,b=2,c=3) # 报错,TypeError: fn() takes 0 positional arguments but 3 positional arguments (and 3 keyword-only arguments) were given
# 如果只有一个不定项参数,那不能使用关键字参数
def add(*nums):
print(add(1,2,3,a=1)) # 不可以
# **作为形参可以接收其他的关键字参数,会将这些参数统一保存在一个字典里
# **不定项关键字形参只有一个,而且必须写在所有参数的最后
# *相当于若干个不定项参数
# **相当于若干个不定项的关键字参数
def fn(**kwargs):
print(kwargs,type(kwargs))
for i in kwargs:
print(i)
fn(a=1,b=2,c=3,d=4)
'''
{'a': 1, 'b': 2, 'c': 3, 'd': 4}
a
b
c
d
'''
3、参数的解包
t只传给了a
def fn(a,b,c):
print(a)
print(b)
print(c)
t = 1,2,3
fn(*t)
'''
1
2
3
'''
def fn(a,b,c):
print(a)
print(b)
print(c)
d = dict(a=1,b=2,c=3)
# d = {'a':1,'b':2,'c':3}
fn(**d)
'''
1
2
3
'''
4、返回值
def add(*nums):
total = 0
for i in nums:
total += i
return total
# 函数也可以返回函数
def fn():
def fn2():
print("hello")
return fn2
a = fn()
a() # hello
# 上两行相当于fn()()
# fn fn()不是一回事情,一个是函数本身,一个是函数的执行结果
print(fn,type(fn))
print(fn(),type(fn()))
'''
.fn2 at 0x000001F597705E50>
'''
# fn是一个函数,fn的执行即fn()也是一个函数
5、函数的帮助文档help()
help(print)
'''
Help on built-in function print in module builtins:
print(...)
print(value, ..., sep=' ', end='n', file=sys.stdout, flush=False)
Prints the values to a stream, or to sys.stdout by default.
Optional keyword arguments:
file: a file-like object (stream); defaults to the current sys.stdout.
sep: string inserted between values, default a space.
end: string appended after the last value, default a newline.
flush: whether to forcibly flush the stream.
'''
6、作用域
作用域分为两种 全局作用域:程序开始时候就创建,程序结束时候销毁 函数作用域:函数执行的时候创建,在调用结束销毁,每次调用都会产生一个新的函数作用域 当我们使用变量的时候,会优先查找当前作用域,如果没有则到上一级查找
a = 10 # globe 全局变量,不太建议去修改全局变量
def fn():
a = 20 # 函数的内部变量,在外部无法访问



