小甲鱼零基础学习python_11 【变量&&闭包&&内嵌函数】

昨天的知识: 函数的变量 & 闭包 & 内嵌

昨天学完小甲鱼的视频以后偷懒没有写博客,今天买了美美的小裙子和巴洛克宫廷风小衬衫还是来补一下昨天的笔记和总结吧~做一个努力的美美的程序媛~


【一】 返回值:

1. python函数跟过程不同,函数一定有返回值;过程可能没有返回值

def hello():
    print('hello world!')
temp=hello()
print(temp)
print(type(temp))
#此时没有返回特定值,函数只返回了none对象

这里写图片描述

2. python返回多个值 可以利用[ 元组 ]或者[ 列表 ]打包返回

def back():
    return(1,2,'a',45.4)
print(back())
temp=back()
print(temp[1])

这里写图片描述


【二】变量:

函数变量的作用域(变量的可见性)问题: 局部变量,全局变量…

(1)

在函数内部可以访问全局变量;

在函数外界尝试访问函数内部的局部变量是错误的,无法访问!

def discounts(price,rate):
    final_price=price*rate
    print("old_price的值:", old_price)  #这里访问全局变量
    return final_price

old_price=float(input('请输入原价:\n'))
rate=float(input('请输入折扣率:\n'))

new_price=discounts(old_price,rate)

print('final_price的值是:', final_price)  #这里尝试访问函数私有变量
print('打折后价格是:', new_price)
print('\n')

这里写图片描述

(2)

在函数里修改全局变量的操作是失败的;因为在函数里的old_price会被当作和全局同名的局部变量,修改的是局部变量

def discounts(price,rate):
    final_price=price*rate
    old_price=88      #这里试图修改全局变量,但是其实修改的是局部变量
    print("修改后old_price的值:", old_price)
    return final_price

old_price=float(input('请输入原价:\n'))
rate=float(input('请输入折扣率:\n'))

new_price=discounts(old_price,rate)

print('修改后的old_price的终极值是:', old_price)  #仍然显示输入的值,而非88
print('打折后价格是:', new_price)

这里写图片描述

这就是python采取屏蔽(shadowing)的方式来保护全局变量

|

但其实也可以在函数内部修改全局变量的值

解决方案: 可以采用global关键字来修改

def discounts2(price,rate):
    final_price=price*rate
    global old_price
    old_price=88     #这里试图修改全局变量,修改成功,因为使用了global关键字
    print("修改后old_price的值:", old_price)
    return final_price

old_price=float(input('请输入原价:\n'))
rate=float(input('请输入折扣率:\n'))

new_price=discounts2(old_price,rate)

print('修改后的old_price的终极值是:', old_price)
print('打折后价格是:', new_price)

这里写图片描述


【三】内嵌函数:

内嵌函数: 在函数内部创建另一个函数
def fuc1():
    print("fuc1正在被调用....")
    def fuc2():
        print("fuc2正在被调用....")
    fuc2()  #内嵌函数:fuc2是定义在fuc1的里面,只能在fuc1里调用
fuc1()
# 在外部直接调用fuc2()是错误的

这里写图片描述


【四】闭包:

如果在一个内部函数里,对外部作用域(但不是在全局作用域)的变量进行引用,那么内部函数则会被认为是闭包。

def fucx(x):
    def fucy(y):
        # fucy对外部作用域fucx(但不是在全局作用域)的变量进行引用,
        # 那么内部函数则会被认为是闭包
        # 所以fucy是一个闭包
        return x*y
    return fucy
i=fucx(8)
print(i)
print(type(i))

这里写图片描述

可以看到这里调用fucx只给了x的入口参数,返回的其实是的fucy,类型是一个function

正确的调用方式:

#调用方式1
print(i(5))
#调用方式2
print(fucx(8)(5))

这里写图片描述

此外注意:

1. 在外部直接调用闭包函数fucy()是错误的!

2. 在内部函数里只能 调用 外部函数局部变量,不能 修改 外部函数的局部变量! 如下:

 def Fuc1():
     x=5
     def fuc2():
         x*=x   #试图修改外部函数局部变量(不是全局变量) 是错误的!会报错!
         return x
     return fuc2()

解决方法1:python2 通过容器类型,比如列表元组等…

因为容器类型不是存放在栈中,所以不会导致问题出现。
def Fuc1():
    x=[5]
    def fuc2():
        x[0]*=x[0]
        return x[0]
    return fuc2()

print(Fuc1())

解决方法2:python3 nonlocal关键字 ,类似于global

def Fuc1():
    x=5
    def fuc2():
        nonlocal x
        x*=x
        return x
    return fuc2()

print(Fuc1())

这里写图片描述

猜你喜欢

转载自blog.csdn.net/Aka_Happy/article/details/81811794