python 参数命名
时间: 2023-07-08 13:43:51 浏览: 53
在 Python 中,参数命名有以下几种常用方式:
1. 位置参数:按照函数定义时参数的顺序进行传参,例如:
```python
def greet(name, message):
print(f"{message}, {name}!")
greet("Alice", "Hello")
```
输出结果为:Hello, Alice!
2. 关键字参数:通过指定参数名进行传参,可以不按照函数定义时参数的顺序进行传参,例如:
```python
def greet(name, message):
print(f"{message}, {name}!")
greet(message="Hello", name="Alice")
```
输出结果为:Hello, Alice!
3. 默认参数:在函数定义时给参数设置默认值,调用时可以不传该参数,使用默认值,例如:
```python
def greet(name, message="Hello"):
print(f"{message}, {name}!")
greet("Alice")
```
输出结果为:Hello, Alice!
4. 可变参数:在函数定义时使用 *args 表示可变参数列表,可以传入任意数量的位置参数,例如:
```python
def greet(*names, message):
for name in names:
print(f"{message}, {name}!")
greet("Alice", "Bob", message="Hello")
```
输出结果为:
Hello, Alice!
Hello, Bob!
5. 关键字可变参数:在函数定义时使用 **kwargs 表示可变关键字参数字典,可以传入任意数量的关键字参数,例如:
```python
def greet(message, **names):
for name, age in names.items():
print(f"{message}, {name}! You are {age} years old.")
greet(message="Hello", Alice=25, Bob=30)
```
输出结果为:
Hello, Alice! You are 25 years old.
Hello, Bob! You are 30 years old.
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![-](https://img-home.csdnimg.cn/images/20210720083327.png)
![-](https://img-home.csdnimg.cn/images/20210720083327.png)
![-](https://img-home.csdnimg.cn/images/20210720083327.png)
![-](https://img-home.csdnimg.cn/images/20210720083327.png)
![-](https://img-home.csdnimg.cn/images/20210720083327.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)