编写程序,完成可变和不可变参数的参数代码
时间: 2024-05-09 18:22:12 浏览: 11
好的,关于可变和不可变参数的参数代码编写,我们可以先从函数的参数传递讲起。
一、参数传递
在Python中,函数的参数传递分为两种:位置参数和关键字参数。位置参数是指直接传入参数值,关键字参数是指使用参数名指定参数值。示例如下:
```python
def add(x, y):
return x + y
add(1, 2) # 位置参数
add(x=1, y=2) # 关键字参数
```
二、可变参数
在函数定义时,我们可以使用星号`*`来表示可变参数。它可以接收任意数量的位置参数。示例如下:
```python
def add(*args):
result = 0
for num in args:
result += num
return result
add(1, 2, 3, 4, 5) # 15
```
当我们传入多个参数时,Python会把这些参数组装成一个tuple,然后再传递给函数。
三、不可变参数
不可变参数指的是函数在调用时传递的参数不可变。比如数字、字符串等。示例如下:
```python
def change_string(s):
s = 'hello'
return s
str1 = 'world'
str2 = change_string(str1)
print(str1) # world
print(str2) # hello
```
在此示例中,我们传递了一个字符串`s`,在函数内部改变了`s`的值,但是在函数外部,原始的字符串`str1`仍然保持不变。
四、可变默认参数
在函数定义时,我们可以给参数设置默认值。如果这个默认值是可变的类型(比如list、dict),那么每次函数调用时,都会使用同一个默认值。
示例代码如下:
```python
def append_item(item, arr=[]):
arr.append(item)
print(arr)
append_item('apple') # ['apple']
append_item('banana') # ['apple', 'banana']
```
在此示例中,我们定义了一个函数`append_item`,它有两个参数:`item`和`arr`。`arr`是一个带有默认值的可变参数。每次调用`append_item`函数时,如果没有传递`arr`参数,就会使用默认值(一个空的列表)。在第一次调用`append_item`函数时,我们传递了参数`'apple'`,此时`arr`的值为`['apple']`。接下来,我们再次调用`append_item`函数,并传递参数`'banana'`,此时`arr`的值不是我们期望的空列表,而是`['apple']`。这是因为每次调用`append_item`函数,都会使用相同的默认参数值。
要避免这种情况的出现,我们可以在函数定义时将可变默认参数设置为`None`,然后在函数内部进行判断。
示例代码如下:
```python
def append_item(item, arr=None):
if arr is None:
arr = []
arr.append(item)
print(arr)
append_item('apple') # ['apple']
append_item('banana') # ['banana']
```
在此示例中,我们对`arr`参数的默认值进行了修改。现在,每次调用`append_item`函数时,如果没有传递`arr`参数,就会使用一个新的空列表。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.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)
![](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)
![](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)