python函数

时间:2021-10-29 13:41:22

一、函数:

创建函数:使用def语句

举例:定义一个返回斐波那楔数列列表的函数

def fibs(num):
result = [0,1]
for i in range(num-2):
result.append(result[-2]+result[-1])
print(result)
fibs(10)

>>>
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34]
>>>

文档化函数:对函数进行说明,写在函数开头的字符串,它会作为函数的一部分进行存储,称为文档字符串。

举例:给square()函数进行注释

def square(x):
'''calculates the square of the nmber x'''
return x*x

#使用此方法访问:
>>> square.__doc__
'calculates the square of the nmber x'
>>>

return语句:函数的返回值,起到结束函数的作用,不需要返回时,返回为None

举例:

def test():
print('pass')
return
print('nothing')
x = test()
print(x) >>>
pass
None
>>>

参数:

形参:函数名后面的变量通常叫做函数的形参;

实参:调用函数时提供的值称为实参;

说明:在函数内为参数赋值新值不会改变外部任何变量的值;

举例:

#不可变参数:字符串、数字和元组
def change(n):
n = 'zyj'
print(n) name = 'sl'
change(name)
print(name)
>>>
zyj
sl
>>> #可变参数如列表
def change(n):
n[0] = 'zyj'
print(n[0]) name = ['sl','xm']
change(name)
print(name) >>>
zyj
['zyj', 'xm']
>>> # 保留原始变量的办法:
def change(n):
n[0] = 'zyj'
print(n[0]) name = ['sl','xm']
change(name[:])
print(name) zyj
['sl', 'xm']
>>>

使用函数改变数据结构的实现举例

要求:编写一个存储名字,并且能根据条件查找对应的名字

实现:定义数据结构类型为字典,通过键值(first,second)查找对应的name。

def init(data):
'''初始化数据结构的函数'''
data['first'] = {}
data['second'] = {}
def lookup(data,lable,name):
'''查找人名相同函数'''
return data[lable].get(name)
def store(data,full_name):
'''将输入名字存储在数据库中函数'''
names = full_name.split()
if len(names) == 1:
names.insert(1, '')
labels = 'first','second'
for label,name in zip(labels,names):
peole = lookup(data,label,name)
if peole:
peole.append(full_name)
else:
data[label][name]=[full_name] >>> storage = {}
>>> init(storage)
>>> storage
{'first': {}, 'second': {}}
>>> store(storage, 'zhao yujiao')
>>> lookup(storage,'second','yujiao')
['zhao yujiao']
>>> store(storage, 'zhao qiaojiao')
>>> lookup(storage,'second','yujiao')
['zhao yujiao']
>>> storage
{'first': {'zhao': ['zhao yujiao', 'zhao qiaojiao']}, 'second': {'yujiao': ['zhao yujiao'], 'qiaojiao': ['zhao qiaojiao']}}
>>> lookup(storage,'first','yujiao')
>>> lookup(storage,'first','zhao')
['zhao yujiao', 'zhao qiaojiao']
>>> store(storage, 'song qiaojiao')
>>> storage
{'first': {'zhao': ['zhao yujiao', 'zhao qiaojiao'], 'song': ['song qiaojiao']}, 'second': {'yujiao': ['zhao yujiao'], 'qiaojiao': ['zhao qiaojiao', 'song qiaojiao']}}
>>> lookup(storage,'second','qiaojiao')
['zhao qiaojiao', 'song qiaojiao']
>>> store(storage, 'qiaojiao')
>>> storage
{'first': {'zhao': ['zhao yujiao', 'zhao qiaojiao'], 'qiaojiao': ['qiaojiao'], 'song': ['song qiaojiao']}, 'second': {'': ['qiaojiao'], 'yujiao': ['zhao yujiao'], 'qiaojiao': ['zhao qiaojiao', 'song qiaojiao']}}

关键字参数:可以明确每个参数的作用,不需要在乎参数的位置。

def hello_1(greeting,name):
print("%s,%s!" % (greeting,name))
def hello_2(name,greeting):
print("%s,%s!" % (name,greeting))
hello_1("Hello","World")
hello_1(greeting="Hello",name="World")
>>>
Hello,World!
Hello,World!
>>>

关键字参数可以在函数中给参数提供默认值,此时调用的时候可以不用提供参数,提供一些或提供所有参数

def hello_3(greeting="Hello",name="World"):
print("%s,%s!" % (greeting,name))
hello_3()
hello_3("greetings")
hello_3("greetings",'zyj')
hello_3(name='zyj')
>>>
Hello,World!
greetings,World!
greetings,zyj!
Hello,zyj!
>>>

位置参数和关键字参数结合使用

def hello_3(name,greeting="Hello",p='!'):
print("%s,%s%s" % (greeting,name,p))
hello_3("zyj")
hello_3("zyj",p='!!!')
hello_3(name='zyj')
>>>
Hello,zyj!
Hello,zyj!!!
Hello,zyj!
>>>

收集参数:参数前加星号将所有值放置在同一个元组中。一个参数里面传递多个值。

def print_params(*params):
print(params)
print_params('zyj')
print_params(1,2,3)
print_params([1],[2],[3])
print_params((1,2),(2,3))
def print_params(title,*params):
print(title)
print(params)
print_params('name:','zyj','sl','sb')
print_params('name:')
>>>
('zyj',)
(1, 2, 3)
([1], [2], [3])
((1, 2), (2, 3))
name:
('zyj', 'sl', 'sb')
name:
()
>>>

收集关键字参数:使用**,返回的是字典

def print_params(**params):
print(params)
print_params(x=1,y=2,z=3)
print_params(x=[1],y=[2],z=[3])
print_params(x=(1,2),y=(2,3))
def print_params(x,y,z=9,*params,**key):
print(x,y,z)
print(params)
print(key)
print_params(1,2,3,4,5,6,foo=1,bar=2)
print_params(1,2)
>>>
{'x': 1, 'y': 2, 'z': 3}
{'x': [1], 'y': [2], 'z': [3]}
{'x': (1, 2), 'y': (2, 3)}
1 2 3
(4, 5, 6)
{'foo': 1, 'bar': 2}
1 2 9
()
{}
>>>

参数收集的逆过程:在定义或者调用参数时使用星号或者双星号传递元组或字典。

def add(x,y):
return x+y
params = (1,2) def hello_3(name,greeting="Hello",p='!'):
print("%s,%s%s" % (greeting,name,p))
params = {'name':"zyj"} >>> add(*params)
3
>>> hello_3(**params)
Hello,zyj!
>>>

作用域:

1、局部变量:函数内部的变量

2、全局变量:具有全局作用域的变量

def foo():
x = 42
x = 1
foo()
>>> x
1
>>>   

当局部变量或者参数的名字和要访问的全局变量名相同时,不能直接访问全局变量,因为全局变量将被局部变量屏蔽

解决办法:使用globals()函数获取全局变量

vars():返回全局变量的字典;

locals():返回局部变量的字典

def combine(params):
print(params+params)
params = 'zyj'
combine('hello')
def combine(params):
print(params+globals()['params'])
params = 'zyj'
combine('hello')
>>>
hellohello
hellozyj
>>>

如何改变全局变量的值:

x = 1
def change_global():
global x
x = x + 1
change_global()
>>> x
2
>>>

函数的嵌套:一般用于需要用一个函数创建另一个的时候;

说明:一个函数位于另一个里面,外层函数返回里层函数,函数本身被返回,但并没有被调用,同时返回的函数可以访问它的定义所在的作用域,来自外部作用域的变量会被内层函数访问。

类似 multiplyByFactor函数存储子封闭作用域的行为叫做闭包。

def multiplier(factor):
def multiplyByFactor(number):
return number*factor
return multiplyByFactor
>>> double = multiplier(2)
>>> double(5)
10
>>> triple = multiplier(3)
>>> triple(3)
9
>>> multiplier(5)(4)
20
>>>

递归:调用自身即函数可以调用自身

无穷递归:会导致程序崩溃或最终返回“超过最大递归深度”的错误信息提示

def foo():
return foo()
>>> foo()
Traceback (most recent call last):
File "<pyshell#0>", line 1, in <module>
foo()
File "C:\Users\七彩蜗牛\Desktop\抽象.py", line 2, in foo
return foo()
File "C:\Users\七彩蜗牛\Desktop\抽象.py", line 2, in foo
return foo()
......
RuntimeError: maximum recursion depth exceeded
>>>

有用的递归:递归实例,包括一个或多个问题较小部分的递归调用

使用递归实现阶乘:函数调用了fact(n)和fact(n-1)两个不同的实体。

def factorial(n):
result = n
for i in range(1,n):
result *= i
return result def fact(n):
if n == 1:
return 1
else:
return n * fact(n-1)
>>> factorial(10)
3628800
>>> fact(10)
3628800
>>>

使用递归实现幂:函数调用了p(x,n)和p(x,n-1)两个不同的实体。

def power(x,n):
result = 1
for i in range(n):
result *= x
return result
def p(x,n):
if n == 0:
return 1
else:
return x * p(x,n-1)
>>>
>>> power(2,3)
8
>>> p(2,3)
8
>>> power(3,0)
1
>>> p(3,0)
1
>>>

函数属性:

命名空间:使用句点属性标识创建不同的名字空间领域。句点属性标识对于两个模块意味不同的命名空间

def foo():
''' foo()---properly created doc string '''
def bar():
pass
bar.__doc__ = 'hello'
bar.version = 0.1
>>>
>>> help(foo)
Help on function foo in module __main__: foo()
foo()---properly created doc string >>> foo()
>>> print(foo())
None
>>> print(bar.version)
0.1
>>> print(bar.__doc__)
hello
>>> help(bar)
Help on function bar in module __main__: bar()
hello >>> bar.__doc__
'hello'
>>> bar.__dict__
{'version': 0.1}
>>> foo.__dict__
{}
>>>