函數嵌套


一、函數的嵌套定義

函數內部定義的函數,無法在函數外部使用內部定義的函數。

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


def circle(radius, action='area'):
    def area():
        return pi * (radius**2)

    def perimeter():
        return 2*pi*radius
    if action == 'area':
        return area()
    else:
        return perimeter()


print(f"circle(10): {circle(10)}")
print(f"circle(10,action='perimeter'): {circle(10,action='perimeter')}")
circle(10): 314.1592653589793
circle(10,action='perimeter'): 62.83185307179586

二、函數的嵌套調用

def max2(x, y):
    if x > y:
        return x
    else:
        return y


def max4(a, b, c, d):
    res1 = max2(a, b)
    res2 = max2(res1, c)
    res3 = max2(res2, d)
    return res3


print(max4(1, 2, 3, 4))
4


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM