函数的对象,函数的嵌套

函数的对象

  • 函数是第一类对象,即函数可以被当作数据处理。
def func():
    pass

print(func)  # 打印函数的内存地址。
             # print(func()) 打印的是函数的返回值。
# <function func at 0x0000006954051EA0>

函数对象的四大功能

1:引用

def index():
    print('from index')

index
f = index  # 可以拿一个变量名去接收函数名。
print(index)
print(f)
# <function index at 0x000000378C821EA0>
# <function index at 0x000000378C821EA0>

2:当作参数传给一个函数

def func():
    print('from func')

def index(type):  # 这里的 type 就是一个变量名,只用来接收值的。
    print('from index')
    type()
index(func)  # 将函数当作参数传给另一个函数。
# from index
# from func

3:可以当作一个函数的返回值

def func():
    print('from func')

def index():
    print('from index')
    return func  # 将函数当作返回值,返回给 index() 调用阶段。
res = index()  # 将其赋值给 res , res 就是 func。
res()  # res() 就等同于 func() 开始调用 func 的函数。 
# from index
# from func

4:可以当作容器类型

def register():
    print('from register')


def login():
    print('from login')


def shopping():
    print('from shopping')


l = [register,login,shopping]
l[0]()  # 通过索引取出 register() 调用函数
l[1]()
l[2]()
# from register
# from login
# from shopping

函数的嵌套

  • 函数嵌套的定义

函数内定义的函数,无法在函数外部使用内部定义的函数。

def f1():
    def f2():
        print('from f2')

    f2()
f2()  # 这样的话会报错
# NameError: name 'f2' is not defined
def f1():
    def f2():
        print('from f2')

    f2()
f1() 
# from f2
  • 现在有个需求,让我们通过函数传参的方式求得某个圆的面积或者周长。
from math import pi         # pi = π

def circle(radius,action):  # radius 半径
    def area():             # area 圆的面积
        return pi * (radius**2)

    def perimeter():        # perimeter 圆的周长
        return 2*pi*radius
    if action == 'area':
        return area()
    else:
        return perimeter()

res = circle(10,'area')
print(res)
res2 = circle(10,'perimeter')
print(res2)
# 314.1592653589793
# 62.83185307179586

函数的嵌套调用

def max1(x,y):
    if x > y:
        return x
    return y

def max2(a,b,c,d):
    res = max1(a,b)
    res2 = max1(res,c)
    res3 = max1(res2,d)
    return res3
print(max2(6,5,4,3))
# 6

转载于:https://www.cnblogs.com/jincoco/p/11164120.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值