Python 函數參數類型詳解
本文將詳細解釋 Python 中不同類型的函數參數,包括位置參數、可變長參數、關鍵字參數、默認參數、關鍵字可變長參數以及關鍵字僅限參數。此外,我們還將探討全局變量、局部變量、嵌套函數以及可變默認參數等相關概念。
1. 位置參數 (Positional Arguments)
位置參數的值按照傳遞順序依次賦值給參數。
<code class="language-python">def greet(first_name, last_name): print("欢迎,", first_name, last_name) greet("张三", "李四") # 输出:欢迎, 张三 李四</code>
<code class="language-python">def calculate_sum(numbers): total = 0 for number in numbers: total += number print(total) scores = [80, 90, 75] calculate_sum(scores) # 输出:245</code>
2. 可變長參數 (Variable-length Arguments)
也稱為任意參數,允許函數接受數量可變的參數。使用 *
前綴表示。
<code class="language-python">def calculate_sum(*numbers): total = 0 for number in numbers: total += number print(total) calculate_sum(10, 20, 30) # 输出:60 calculate_sum(5, 15, 25, 35) # 输出:80 calculate_sum() # 输出:0</code>
3. 關鍵字參數 (Keyword Arguments)
通過參數名賦值,調用函數時可以不按順序傳遞參數。
<code class="language-python">def greet(name, greeting="你好"): print(greeting, name) greet(name="王五", greeting="早上好") # 输出:早上好 王五 greet(name="赵六") # 输出:你好 赵六</code>
4. 默認參數 (Default Arguments)
參數具有默認值,調用函數時可以省略該參數。
<code class="language-python">def login(username, password="password123"): print(username, password) login("admin") # 输出:admin password123 login("user", "mypassword") # 输出:user mypassword</code>
5. 關鍵字可變長參數 (Keyword Variable-length Arguments)
允許傳遞任意數量的關鍵字參數,使用 **
前綴表示,參數以字典形式存儲。
<code class="language-python">def user_info(**kwargs): print(kwargs) user_info(name="孙七", age=30, city="北京") # 输出:{'name': '孙七', 'age': 30, 'city': '北京'}</code>
6. 關鍵字僅限參數 (Keyword-only Arguments)
調用函數時必須指定參數名,使用 *
在函數簽名中分隔位置參數和關鍵字僅限參數。
<code class="language-python">def add(*, num1, num2): return num1 + num2 print(add(num1=100, num2=200)) # 输出:300 # print(add(100, 200)) # 报错:TypeError</code>
7. 函數返回字典 (Function Returning Dictionary)
函數可以創建並返回字典對象。 zip()
函數將多個列表元素組合成元組,dict()
函數將元組轉換為字典。
<code class="language-python">def create_player_stats(names, scores): return dict(zip(names, scores)) names = ["A", "B", "C"] scores = [10, 20, 30] stats = create_player_stats(names, scores) print(stats) # 输出:{'A': 10, 'B': 20, 'C': 30}</code>
8. 可變默認參數 (Mutable Default Arguments)
使用列表或字典作為默認參數時,需要注意,它只初始化一次。如果在函數調用中修改了默認參數,則修改後的值會保留在後續調用中。建議使用 None
作為默認值,並在函數內部創建新的可變對象。
<code class="language-python">def add_to_list(number, my_list=None): if my_list is None: my_list = [] my_list.append(number) return my_list print(add_to_list(10)) # 输出:[10] print(add_to_list(20)) # 输出:[20]</code>
9. 全局變量 (Global Variables)
在所有函數之外定義的變量。
<code class="language-python">global_var = 100 def access_global(): print(global_var) access_global() # 输出:100</code>
10. 局部變量 (Local Variables)
在函數或代碼塊內部定義的變量。
<code class="language-python">def local_scope(): local_var = 200 print(local_var) local_scope() # 输出:200 # print(local_var) # 报错:NameError</code>
11. 嵌套函數 (Inner Functions)
在其他函數內部定義的函數。內部函數可以訪問外部函數的變量。使用 nonlocal
關鍵字可以修改外部函數的變量。
<code class="language-python">def outer_function(): outer_var = 300 def inner_function(): nonlocal outer_var outer_var += 100 print("inner:", outer_var) inner_function() print("outer:", outer_var) outer_function() # 输出:inner: 400, outer: 400</code>
通過以上示例,您可以更清晰地理解 Python 中各種函數參數類型的用法和特性,並避免在使用過程中出現常見的錯誤。 記住,理解可變默認參數的陷阱並採取適當的措施至關重要。
以上是一天 - python中的論點類型的詳細內容。更多資訊請關注PHP中文網其他相關文章!