Python基礎:自定義函數


函數的形式:

def name(param1, param2, ..., paramN):
    statements
    return/yield value # optional
  • 和其他需要編譯的語言(比如 C 語言)不一樣的是,def 是可執行語句,這意味着函數直到被調用前,都是不存在的。當程序調用函數時,def 語句才會創建一個新的函數對象,並賦予其名字。
  • Python 是 dynamically typed ,對函數參數來說,可以接受任何數據類型,這種行為在編程語言中稱為多態。所以在函數里必要時要做類型檢查,否則可能會出現例如字符串與整形相加出異常的情況。

函數的嵌套:

  例:

def f1():
    print('hello')
    def f2():
        print('world')
    f2()
f1()
'hello'
'world'

  嵌套函數的作用

  • 保證內部函數的隱私
def connect_DB():
    def get_DB_configuration():
        ...
        return host, username, password
    conn = connector.connect(get_DB_configuration())
    return conn

  在connect_DB函數外部,並不能直接訪問內部函數get_DB_configuration,提高了程序的安全性

  • 如果在需要輸入檢查不是很快,還會耗費一定資源時,可以使用函數嵌套提高運行效率。
def factorial(input):
    # validation check
    if not isinstance(input, int):
        raise Exception('input must be an integer.')
    if input < 0:
        raise Exception('input must be greater or equal to 0' )
    ...

    def inner_factorial(input):
        if input <= 1:
            return 1
        return input * inner_factorial(input-1)
    return inner_factorial(input)
print(factorial(5))

函數作用域

  1.global

  在Python中,我們不能在函數內部隨意改變全局變量的值,會報local variable 'VALUE' referenced before assignment。

  下例通過global聲明,告訴解釋器VALUE是全局變量,不是局部變量,也不是全新變量
VALUE = 10
LIST = ['a','b']
print(id(LIST)) #2490616668744
def validation_check(value):
    global VALUE
    VALUE += 3 #如果注釋掉global VALUE,會報local variable 'VALUE' referenced before assignment
    
    LIST[0] = 10 #可變類型無需global可以使用全局變量?
    print(id(LIST)) #2490616668744
    print(f'in the function VALUE: {LIST}') #in the function VALUE: [10, 'b']
    print(f'in the function VALUE: {VALUE}') #in the function VALUE: 13

validation_check(1)
print(f'out of function {LIST}') #out of function [10, 'b']
print(f'out of function {VALUE}') #out of function 13
#a: 13
#b: 13

  2.nonlocal

  對於嵌套函數,nonlocal 聲明變量是外部函數中的變量

  

def outer():
    x = "local"
    def inner():
        nonlocal x # nonlocal 關鍵字表示這里的 x 就是外部函數 outer 定義的變量 x
        x = 'nonlocal'
        print("inner:", x)
    inner()
    print("outer:", x)
outer()
# inner :nonlocal
# outer :nonlocal
  當內部變量與外部變量同名時,內部變量會覆蓋外部變量
def outer():
    x = "local"
    def inner():
        x = 'nonlocal' # 這里的 x 是 inner 這個函數的局部變量
        print("inner:", x)
    inner()
    print("outer:", x)
outer()
# 輸出
# inner: nonlocal
# outer: local

閉包

  • 內部函數返回一個函數
  • 外部函數nth_power()中的exponent參數在執行完nth_power()后仍然會被內部函數exponent_of記住
def nth_power(exponent):
    def exponent_of(base):
        return base ** exponent
    return exponent_of # 返回值是 exponent_of 函數

square = nth_power(2) # 計算一個數的平方
cube = nth_power(3) # 計算一個數的立方 
# square
# # 輸出
# <function __main__.nth_power.<locals>.exponent(base)>

# cube
# # 輸出
# <function __main__.nth_power.<locals>.exponent(base)>

# print(square(2))  # 計算 2 的平方
# print(cube(2)) # 計算 2 的立方
# # 輸出
# 4 # 2^2
# 8 # 2^3

參考:

  極客時間《Python核心技術與實戰 》


免責聲明!

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



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