在Python中,函數(shù)參數(shù)可以通過以下幾種方式進行設(shè)置:
def greet(name):
print("Hello, " + name)
greet("Alice") # 正確的用法
greet() # 錯誤的用法,缺少必需參數(shù)
def greet(name, age):
print("Hello, " + name + ". You are " + str(age) + " years old.")
greet(age=30, name="Bob") # 正確的用法,使用關(guān)鍵字參數(shù)
def greet(name, greeting="Hello"):
print(greeting + ", " + name)
greet("Alice") # 輸出 "Hello, Alice"
greet("Bob", greeting="Hi") # 輸出 "Hi, Bob"
def example_function(arg1, *args, **kwargs):
print("Required argument:", arg1)
print("Non-keyword variable arguments:", args)
print("Keyword variable arguments:", kwargs)
example_function(1, 2, 3, 4, key1="value1", key2="value2")
輸出:
Required argument: 1
Non-keyword variable arguments: (2, 3, 4)
Keyword variable arguments: {'key1': 'value1', 'key2': 'value2'}
綜上所述,Python函數(shù)參數(shù)設(shè)置有多種方式,可以根據(jù)實際需求選擇合適的參數(shù)類型。