Python第六章 函数

与java方法的不同,Python的函数也可当成一个对象,可以参数是函数,也可返回值是函数

定义

  • 以def关键字开头,不带表达式的return的表达式相当于return none;
def printme(str):
    print(str)

printme("我要调用用户自定义函数!")  # 我要调用用户自定义函数!
printme("再次调用同一函数")  # 再次调用同一函数
temp = printme('hello') # hello
print(temp)  # None

帮助文档,help(函数名):现实这个函数的信息

函数参数

1,函数调用可以:myfun(name=‘张三’,age=26)

位置参数

  • 就是普通参数,想想java的参数就好了(但是不带类型,取决于函数体内部怎么用就是什么类型)
def functionname(arg1):
    "函数_文档字符串"
    function_suite
    return [expression]

arg1 位置参数,在不指定参数名的时候,必须按照顺序放入参数–就是普通java函数使用规则,参数必须跟定义的位置一样

默认参数

  • 在定义函数的时候,fun(name,age=8),这样写死的参数就是默认参数,如果使用的时候该属性不做传参就会使用默认的值
def printinfo(name, age=8):
    print('Name:{0},Age:{1}'.format(name, age))


printinfo('小马')  # Name:小马,Age:8
printinfo('小马', 10)  # Name:小马,Age:10
----------

def myself(name,age=18,sex):
    return '我是'+ name+",今年"+str(age)+'岁,性别:'+sex
print(myself('徐磊',26,'男'))

# non-default argument follows default argument

默认参数一定要放在位置参数 后面,不然程序会报错,就是把默认参数放在参数的最后位置就好了

可变参数(*arg-元组参数)

  • 参数个数可变__(*atgs)__;在函数调用的时候自动把args组装成一个元组(tuple),函数体取值的时候要把args当成元组来处理!!
def printinfo(arg1, *args):
    print(arg1)
    for var in args:
        print(var)


printinfo(10)  # 10
printinfo(70, 60, 50)

# 70
# 60
# 50

关键字参数(**arg-字典参数)

  • 也是参数个数可变__(**args)__;与可变参数不同的是:在函数内部自动组装成一个字典(dict)
def printinfo(arg1, *args):
    print(arg1)
    for var in args:
        print(var)


printinfo(10)  # 10
printinfo(70, 60, 50)

# 70
# 60
# 50

参数重得放入key=value的形式,才能自动组装成字典的哟(字典其实也就睡java 的map类型😂);

命名关键字参数(*,参数名)

  • 位置参数,按照位置来穿参数,可以直接穿一个值,也可以是key=value 的形式,但是关键字参数必须是key=value的形式传值;*,参数:这个*号当成一个标志就行了
def printinfo(arg1, *, nkw, **kwargs):
    print(arg1)
    print(nkw)
    print(kwargs)


printinfo(70, nkw=10, a=1, b=2)
# 70
# 10
# {'a': 1, 'b': 2}

printinfo(70, 10, a=1, b=2)
# TypeError: printinfo() takes 1 positional argument but 2 were given

没有写参数名nwk,因此 10 被当成「位置参数」,而原函数只有 1 个位置函数,现在调用了 2 个,因此程序会报错。

组合参数

  • 有顺序规定
    在 Python 中定义函数,可以用位置参数、默认参数、可变参数、命名关键字参数和关键字参数,这 5 种参数中的 4 个都可以一起使用,但是注意,参数定义的顺序必须是:
    位置参数、默认参数、可变参数和关键字参数。
    位置参数、默认参数、命名关键字参数和关键字参数
    要注意定义可变参数和关键字参数的语法:
    *args 是可变参数,args 接收的是一个 tuple
    **kw 是关键字参数,kw 接收的是一个 dict

变量作用域

  • Python 中,程序的变量并不是在哪个位置都可以访问的,访问权限决定于这个变量是在哪里赋值的。
  • 定义在函数内部的变量拥有局部作用域,该变量称为局部变量。
  • 定义在函数外部的变量拥有全局作用域,该变量称为全局变量。
  • 局部变量只能在其被声明的函数内部访问,而全局变量可以在整个程序范围内访问。
def discounts(price, rate):
    final_price = price * rate
    return final_price


old_price = float(input('请输入原价:'))  # 98
rate = float(input('请输入折扣率:'))  # 0.9
new_price = discounts(old_price, rate)
print('打折后价格是:%.2f' % new_price)  # 88.20
  • 当内部作用域想修改外部作用域的变量时,就要用到global和nonlocal关键字了,好比,用global来修改了一下这个变量的范围的效果!!
num = 1

def fun1():
    global num  # 需要使用 global 关键字声明
    print(num)  # 1
    num = 123
    print(num)  # 123

fun1()
print(num)  # 123

内嵌函数

  • 在函数内部定义一个函数;内部定义的函数作用域尽在函数内部
def outer():
    print('outer函数在这被调用')

    def inner():
        print('inner函数在这被调用')

    inner()


outer()
# outer函数在这被调用
# inner函数在这被调用

闭包

  • 一种内嵌函数,内嵌函数内调用外层函数的局部变量;通过闭包可以访问外层函数的局部变量,这个作用域称为__闭包作用域__。
def funX(x):
    def funY(y):
        return x * y

    return funY


i = funX(8)
print(type(i))  # <class 'function'>
print(i(5))  # 40
  • 闭包的返回值通常是__函数__(就一个函数名,不带括号的哟),有点像java重的set()函数的功能了。
def make_counter(init):
    counter = [init]

    def inc(): counter[0] += 1

    def dec(): counter[0] -= 1

    def get(): return counter[0]

    def reset(): counter[0] = init

    return inc, dec, get, reset


inc, dec, get, reset = make_counter(0)
inc()
inc()
inc()
print(get())  # 3
dec()
print(get())  # 2
reset()
print(get())  # 0
  • 闭包好处:1这个闭包函数有点像java重的get和set方法;从外部访问函数内部的变量;2还有一个好处是让这些变量的值始终保存在内存中(也可以理解为保留当前运行环境)
 def download_enter(download_times):
    def download():
        nonlocal download_times
        download_times += 1
        print("This is the %s time download" % download_times)
    return download

 
>>> d = download_enter(0)
>>> d()
This is the 1 time download
>>> d()
This is the 2 time download
>>> d()
This is the 3 time download
----------------------

def make_filter(keep):  
    def the_filter(file_name):  
        file = open(file_name)  
        lines = file.readlines()  
        file.close()  
        filter_doc = [i for i in lines if keep in i]  
        return filter_doc  
    return the_filter  

filter = make_filter("pass")  
filter_result = filter("result.txt") 
  • 如果要修改闭包作用域中的变量则需要关键字nonlocal,跟global一样,内部改外部
def outer():
    num = 10

    def inner():
        nonlocal num  # nonlocal关键字声明
        num = 100
        print(num)

    inner()
    print(num)


outer()

# 100
# 100

递归

  • 递归是一种编程思想;在函数内部调用自己;可以通过import sys;

sys.==setrecursionlimit(1000)==设置递归层数!!!

# 求n的阶乘
#利用循环
n = 5
for k in range(1, 5):
    n = n * k
print(n)  # 120

# 利用递归
def factorial(n):
    if n == 1:
        return 1
    return n * factorial(n - 1)

print(factorial(5)) # 120
-------------------------------
#求 斐波那契数列 0 1 1 2 3 5 8.....
# 利用循环
i = 0
j = 1
lst = list([i, j])
for k in range(2, 11):
    k = i + j
    lst.append(k)
    i = j
    j = k
print(lst)  
# [0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55]

# 利用递归
def recur_fibo(n):
    if n <= 1:
        return n
    return recur_fibo(n - 1) + recur_fibo(n - 2)


lst = list()
for k in range(11):
    lst.append(recur_fibo(k))
print(lst)  
# [0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55]

Lambda函数

  • 除了用def定义函数外,还能用lambda定义匿名函数;Lambda不是显示的return返回,表达式本身就是一个返回!有自己的命名空间,只能反问冒号之前的参数;

lambda argument_list: expression

  • expression 只能是一个表达式,输入函数参数,输出一些值。
def sqr(x):
    return x ** 2


print(sqr)
# <function sqr at 0x000000BABD3A4400>

y = [sqr(x) for x in range(10)]
print(y)
# [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

lbd_sqr = lambda x: x ** 2
print(lbd_sqr)
# <function <lambda> at 0x000000BABB6AC1E0>

y = [lbd_sqr(x) for x in range(10)]
print(y)
# [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]


sumary = lambda arg1, arg2: arg1 + arg2
print(sumary(10, 20))  # 30

func = lambda *args: sum(args)
print(func(1, 2, 3, 4, 5))  # 15

匿名函数应用

  • 函数式编程 是指代码中每一块都是不可变的,都由纯函数的形式组成。这里的纯函数,是指函数本身相互独立、互不影响,对于相同的输入,总会有相同的输出,没有任何副作用。
#非函数式编程
def f(x):
    for i in range(0, len(x)):
        x[i] += 10
    return x


x = [1, 2, 3]
f(x)
print(x)
# [11, 12, 13]

-------------------

#函数式编程
def f(x):
    y = []
    for item in x:
        y.append(item + 10)
    return y


x = [1, 2, 3]
f(x)
print(x)
# [1, 2, 3]
  • 匿名函数 常常应用于函数式编程的高阶函数 (high-order function)中,主要有两种形式:

    • 参数是函数 (filter, map)
    • 返回值是函数 (closure)
  • filter(function, iterable) 过滤序列,过滤掉不符合条件的元素,返回一个迭代器对象,如果要转换为列表,可以使用 list() 来转换。

odd = lambda x: x % 2 == 1
templist = filter(odd, [1, 2, 3, 4, 5, 6, 7, 8, 9])
print(list(templist))  # [1, 3, 5, 7, 9]
  • map(function, *iterables) 根据提供的函数对指定序列做映射
m1 = map(lambda x: x ** 2, [1, 2, 3, 4, 5])
print(list(m1))  
# [1, 4, 9, 16, 25]

m2 = map(lambda x, y: x + y, [1, 3, 5, 7, 9], [2, 4, 6, 8, 10])
print(list(m2))  
# [3, 7, 11, 15, 19]
  • 自定义 高阶函数
def apply_to_list(fun, some_list):
    return fun(some_list)

lst = [1, 2, 3, 4, 5]
print(apply_to_list(sum, lst))
# 15

print(apply_to_list(len, lst))
# 5

print(apply_to_list(lambda x: sum(x) / len(x), lst))
# 3.0
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值