函数的对象,函数的嵌套

函数的对象

  • 函数是第一类对象,即函数可以被当作数据处理。
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