Python学习笔记(函数篇上)

小扩展:
函数和方法的区别

函数属于整个文件, 方法属于某一个类, 方法如果离开类就不可调用

函数可以直接调用, 方法必须用对象或者类来调用
注意: 虽然函数属于整个文件, 但是如果把函数写在类的声明中会不识别

不能把函数当做方法来调用, 也不能把方法当做函数来调用

1.深浅拷贝

浅拷贝:通常使用copy方法或者切片,这种拷贝的特点是只拷贝第一层,一旦存在嵌套,嵌套里的元素变化会影响到原对象的变化

深拷贝:要使用copy模块里的deepcopy方法,拷贝之后原对象和拷贝对象为两个独立的对象,互不影响

s = [[1, 2], 'hack', 'age']
s1 = s.copy()	#浅拷贝,只拷贝第一层,s1列表改变会影响s
import copy
s2 = copy.deepcopy(s)	#深拷贝,全拷贝,s2改变不影响s

2.函数

2.1 函数的作用

​ 减少重复代码

​ 方便修改,更易扩展

​ 保持代码一致性

2.2 函数的定义

使用def关键字定义对象,函数名的命名规则与变量名相同,注意‘ : ’结尾,下面跟的是函数段

def demo01():
    print('Hello,world')

print(demo01)
demo01()	# 调用用函数名加括号
2.3函数的参数

(1)( 顺序)必需参数:形参与实参顺序上一一对应

(2)关键字参数

(3)默认参数:要跟在其他参数后面

def print_inf(name, age, sex):
    print('Name: %s'% name)
    print('Age: %d'% age)
    print('Sex: %s'% sex)

#顺序参数 positional argument
print_inf('hack', 19, 'male')   
#关键字参数 keyword argument
print_inf(sex='male',name='hack',age=19)    

def print_inf(name, age, sex='male'):
    print('Name: %s'% name)
    print('Age: %d'% age)
    print('Sex: %s'% sex)


print_inf('hack', 19)   #默认参数 如没有声明sex为其他值,sex='male'
print_inf('Aaron', 20)

(4)不定长参数

*args 将传递的参数组成元组给args 无命名参数

**kwargs 将传递的参数做成字典传给kwargs 命名参数

def print_inf(*args,**kwargs):  # *args,*kwargs为不定长参数,其中前者接收未命名参数,把参数组成元组给args
    #print(kwargs)               # 后者接受命名参数,把参数组成字典给kwargs
    #print(args)
    for key in kwargs:
        print('%s: %s'% (key,kwargs[key]))
    for i in args:
        print(i)


print_inf('hack',19,'male',hobby='sport',height=183)

结果:hobby: sport
height: 183
hack
19
male

kwargs :{‘hobby’: ‘sport’, ‘height’: 183}

args : (‘hack’, 19, ‘male’)

针对字典和列表的传参:

def print_inf(*args):
    print(args)

print_inf(['hack',19])      #(['hack', 19],)
print_inf(*['hack',19])     #('hack', 19)

def print_inf(**kwargs):
    print(kwargs)

inf = {'name':'hack','age':19}
print_inf(name='hack',age=19)
print_inf(**inf)    #{'name': 'hack', 'age': 19}

*参数顺序:def(non-default, default, args, kwargs)
即:非默认参数,默认参数,不定长参数

2.4函数的返回值

(1)函数无return,默认返回none

(2)函数在执行过程中遇见return,就会停止执行并返回结果

(3)return多个对象,会将他们组成元组进行返回

2.5作用域 LEGB

(1)local:局部作用域

(2)enclosing:父级函数的局部作用域

(3)global:全局变量

(4)built-in:内置函数

注:

(1)变量查找顺序: 局部作用域>父级局部>全局变量>python内置作用域

(2)全局变量在局部作用域中不能被修改,要想修改,用关键字global声明

(3)父级函数里变量在子集函数中不可被修改,要想修改,用关键字nonlocal声明

num = int(2.9)  #int为 built-in

a = 10  #a为global变量
def outer():
    x = 2  #enclosing

    def inter():
        y = 3   #local变量
        print(x)	#里层无x变量,向外层寻找
    inter()

outer()
2.6 高阶函数

注:(1)函数名字可以进行赋值

​ (2)函数名可以作为函数参数,也可以作为函数的返回值

def f(n):
    return n*n

def foo(a,b,func):
    return func(a)+func(b)	# func与f是同一函数引用

print(foo(2,4,f))	#将函数名f作为参数传递
2.7 递归函数

(1)自己调用自己

(2)需要添加结束条件结束递归

(3)递归效率不高,次数过多会导致栈溢出

def foo(n):
    if n==1:
        return 1
    return n*foo(n-1)


print(foo(4))
2.8 内置函数

(1)all() 判断可迭代对象中是否所有布尔值都为真

"""
Return True if bool(x) is True for all values x in the iterable.

If the iterable is empty, return True.
"""
print(all([1,2,3])) # True

(2)eval() 将字符串转换为字典

(3)filter(func,*iterable)

将可迭代对象值传到函数执行,返回符合条件的值生成迭代器(过滤)

"""
filter(function or None, iterable) --> filter object

Return an iterator yielding those items of iterable for which function(item)
is true. If function is None, return the items that are true.
"""
def f(n):
    if n>2:
        return n
ret=filter(f,[2,3,4])
print(ret)  #<filter object at 0x00000203D92C8A60>
print(list(ret))    #[3, 4]

(4)map(func,*iterable)

将可迭代对象每一个值传到函数执行,并且返回生成迭代器(处理)

"""
map(func, *iterables) --> map object

Make an iterator that computes the function using arguments from
each of the iterables.  Stops when the shortest iterable is exhausted.
"""
def f(n):
    if n>2:
        return n

ret=map(f,[2,3,4])
print(ret)  #<<map object at 0x000002525C528A60>
print(list(ret))    #[None, 3, 4]

(5)reduce(function,sequence)

要引入 from functools import reduce

包含两个参数的函数累计应用于序列的项,从左到右,直到序列缩减为一个值(结果为一个值)

from functools import reduce
def mul(x,y):
    return x*y

ret = reduce(mul,range(1,6))
print(ret)  #1*2*3*4*5=120
# 执行操作:[1,2,3,4,5]->[1*2,3,4,5]->[6,4,5]->[24,5]->120

(6)lambda 匿名函数

ret = lambda x,y : x+y
print(ret(2,3))	# 5 
from functools import reduce
print(reduce(lambda x,y: x+y, range(1,6)))

(7)next 只针对迭代器

"""
next(iterator[, default])

Return the next item from the iterator. If default is given and the iterator
is exhausted, it is returned instead of raising StopIteration.
"""

(8)iter 对于可迭代对象

(9)isinstance():用于判断变量是否属于某一类型,属于返回True

=====================================

函数的重点修饰器,生成器,迭代器见下篇哦

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值