文章目錄
- 定義自定義函數的基本語法
- 參數類型
- 示例代碼
- 函數作用域
- 匿名函數(Lambda)
- 閉包
- 裝飾器
Python中的自定義函數允許你編寫一段可重用的代碼塊,這段代碼可以帶參數(輸入),并可能返回一個值(輸出)。自定義函數可以提高代碼的可讀性、重用性和組織性。下面是詳細介紹和示例。
定義自定義函數的基本語法
def function_name(parameters):# 函數體# ...return value # 可選,函數可以沒有返回值
function_name
:函數名,遵循Python的命名規則。parameters
:函數可以接受的參數列表,可以有零個或多個參數。return value
:函數返回的值,可以是任何數據類型,也可以省略,表示返回None
。
參數類型
- 位置參數:必須按順序提供。
- 默認參數:可以提供默認值,調用時可以不傳遞。
- 關鍵字參數:允許指定參數名,提高函數調用的靈活性。
- 可變參數:可以接受任意數量的位置參數。
- 關鍵字可變參數:可以接受任意數量的關鍵字參數。
示例代碼
- 示例1:基本自定義函數
def greet(name):return f"Hello, {name}!"print(greet("Alice")) # 輸出: Hello, Alice!
- 示例2:帶有默認參數的函數
def greet(name, message="Good morning"):return f"{message}, {name}!"print(greet("Bob")) # 輸出: Good morning, Bob!
print(greet("Charlie", "Good evening")) # 輸出: Good evening, Charlie!
- 示例3:帶有可變參數的函數
def sum_numbers(*numbers):total = 0for num in numbers:total += numreturn totalprint(sum_numbers(1, 2, 3, 4)) # 輸出: 10
- 示例4:帶有關鍵字可變參數的函數
def print_info(**kwargs):for key, value in kwargs.items():print(f"{key}: {value}")print_info(name="Dave", age=30, job="Developer")
# 輸出:
# name: Dave
# age: 30
# job: Developer
- 示例5:使用類型注解
Python 3.5+ 支持類型注解,可以提高代碼的可讀性和健壯性。
def greet(name: str, message: str = "Good morning") -> str:return f"{message}, {name}!"print(greet("Eve")) # 輸出: Good morning, Eve!
函數作用域
在Python中,函數有自己的命名空間。這意味著在函數內部定義的變量不能在外部訪問,除非它們被返回并賦值給外部變量。
def get_secret():secret = "I am a secret!"return secretmy_secret = get_secret()
print(my_secret) # 可以訪問返回的值
# print(secret) # 會拋出錯誤,因為secret在函數外部不可訪問
匿名函數(Lambda)
Python也支持匿名函數,使用lambda
關鍵字定義,通常用于簡單的函數。
add = lambda x, y: x + y
print(add(5, 3)) # 輸出: 8
閉包
閉包是指一個函數能夠記住其外部環境的狀態。這通常通過在函數內部定義另一個函數來實現。
def make_counter():count = 0def counter():nonlocal countcount += 1return countreturn countermy_counter = make_counter()
print(my_counter()) # 輸出: 1
print(my_counter()) # 輸出: 2
裝飾器
裝飾器是Python中的一個高級功能,它允許你在不修改函數本身的情況下增加函數的功能。
def my_decorator(func):def wrapper():print("Something is happening before the function is called.")func()print("Something is happening after the function is called.")return wrapper@my_decorator
def say_hello():print("Hello!")say_hello()
# 輸出:
# Something is happening before the function is called.
# Hello!
# Something is happening after the function is called.
蒼天不負有心人!