python函数中参数定义
时间: 2023-11-17 17:06:14 浏览: 95
在Python函数中,参数可以通过以下方式定义:
1. 位置参数:这是最常见的参数类型。它们按照定义的顺序传递给函数。例如:
```python
def greet(name, message):
print(f"{message}, {name}!")
greet("John", "Hello")
# Output: Hello, John!
```
2. 关键字参数:使用关键字指定参数的名称,这样它们可以以任意顺序传递给函数。例如:
```python
def greet(name, message):
print(f"{message}, {name}!")
greet(message="Hello", name="John")
# Output: Hello, John!
```
3. 默认参数:这些参数具有默认值,如果没有传递,则使用默认值。例如:
```python
def greet(name, message="Hello"):
print(f"{message}, {name}!")
greet("John")
# Output: Hello, John!
greet("John", "Hi")
# Output: Hi, John!
```
4. 可变参数:这些参数允许你传递任意数量的参数。它们有两种形式:*args和**kwargs。*args表示一个元组,**kwargs表示一个字典。例如:
```python
def greet(*names):
for name in names:
print(f"Hello, {name}!")
greet("John", "Mary", "Tom")
# Output:
# Hello, John!
# Hello, Mary!
# Hello, Tom!
def greet(**names):
for key, value in names.items():
print(f"{key}: {value}")
greet(name1="John", name2="Mary", name3="Tom")
# Output:
# name1: John
# name2: Mary
# name3: Tom
```
在定义函数时,可以混合使用这些参数类型。例如:
```python
def greet(name, message="Hello", *args, **kwargs):
print(f"{message}, {name}!")
for arg in args:
print(f"Hi, {arg}!")
for key, value in kwargs.items():
print(f"{key}: {value}")
greet("John")
# Output: Hello, John!
greet("John", "Hi", "Mary", "Tom", age=30, city="New York")
# Output:
# Hi, Mary!
# Hi, Tom!
# age: 30
# city: New York
```
阅读全文