Skip to content

Commit e1fd8b2

Browse files
暮晨ducheng
暮晨
authored and
ducheng
committed
EX.Beware of default mutable arguments
1 parent d63a590 commit e1fd8b2

File tree

1 file changed

+6
-6
lines changed

1 file changed

+6
-6
lines changed

README.md

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -59,7 +59,7 @@ So, here we go...
5959
- [> Stubborn `del` operator/坚强的 `del` *](#-stubborn-del-operator坚强的-del-)
6060
- [> Deleting a list item while iterating/迭代列表时删除元素](#-deleting-a-list-item-while-iterating迭代列表时删除元素)
6161
- [> Loop variables leaking out!/循环变量泄漏!](#-loop-variables-leaking-out循环变量泄漏)
62-
- [> Beware of default mutable arguments!](#-beware-of-default-mutable-arguments)
62+
- [> Beware of default mutable arguments!/当心默认的可变参数!](#-beware-of-default-mutable-arguments当心默认的可变参数)
6363
- [> Catching the Exceptions](#-catching-the-exceptions)
6464
- [> Same operands, different story!](#-same-operands-different-story)
6565
- [> The out of scope variable](#-the-out-of-scope-variable)
@@ -1543,7 +1543,7 @@ print(x, ': x in global')
15431543
15441544
---
15451545
1546-
### > Beware of default mutable arguments!
1546+
### > Beware of default mutable arguments!/当心默认的可变参数!
15471547
15481548
```py
15491549
def some_func(default_arg=[]):
@@ -1563,9 +1563,9 @@ def some_func(default_arg=[]):
15631563
['some_string', 'some_string', 'some_string']
15641564
```
15651565
1566-
#### 💡 Explanation:
1566+
#### 💡 说明:
15671567
1568-
- The default mutable arguments of functions in Python aren't really initialized every time you call the function. Instead, the recently assigned value to them is used as the default value. When we explicitly passed `[]` to `some_func` as the argument, the default value of the `default_arg` variable was not used, so the function returned as expected.
1568+
- Python中函数的默认可变参数并不是每次调用该函数时都会被初始化. 相反, 它们会使用最近分配的值作为默认值. 当我们明确的将 `[]` 作为参数传递给 `some_func` 的时候, 就不会使用 `default_arg` 的默认值, 所以函数会返回我们所期望的结果.
15691569
15701570
```py
15711571
def some_func(default_arg=[]):
@@ -1575,7 +1575,7 @@ def some_func(default_arg=[]):
15751575
15761576
**Output:**
15771577
```py
1578-
>>> some_func.__defaults__ #This will show the default argument values for the function
1578+
>>> some_func.__defaults__ # 这里会显示函数的默认参数的值
15791579
([],)
15801580
>>> some_func()
15811581
>>> some_func.__defaults__
@@ -1588,7 +1588,7 @@ def some_func(default_arg=[]):
15881588
(['some_string', 'some_string'],)
15891589
```
15901590
1591-
- A common practice to avoid bugs due to mutable arguments is to assign `None` as the default value and later check if any value is passed to the function corresponding to that argument. Example:
1591+
- 避免可变参数导致的错误的常见做法是将 `None` 指定为参数的默认值, 然后检查是否有值传给对应的参数. 例:
15921592
15931593
```py
15941594
def some_func(default_arg=None):

0 commit comments

Comments
 (0)