Skip to content

Commit 4c2027f

Browse files
暮晨leisurelicht
暮晨
authored andcommitted
EX.Beware of default mutable arguments
1 parent 9382617 commit 4c2027f

File tree

1 file changed

+6
-6
lines changed

1 file changed

+6
-6
lines changed

README.md

+6-6
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)
@@ -1548,7 +1548,7 @@ print(x, ': x in global')
15481548
15491549
---
15501550
1551-
### > Beware of default mutable arguments!
1551+
### > Beware of default mutable arguments!/当心默认的可变参数!
15521552
15531553
```py
15541554
def some_func(default_arg=[]):
@@ -1568,9 +1568,9 @@ def some_func(default_arg=[]):
15681568
['some_string', 'some_string', 'some_string']
15691569
```
15701570
1571-
#### 💡 Explanation:
1571+
#### 💡 说明:
15721572
1573-
- 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.
1573+
- Python中函数的默认可变参数并不是每次调用该函数时都会被初始化. 相反, 它们会使用最近分配的值作为默认值. 当我们明确的将 `[]` 作为参数传递给 `some_func` 的时候, 就不会使用 `default_arg` 的默认值, 所以函数会返回我们所期望的结果.
15741574
15751575
```py
15761576
def some_func(default_arg=[]):
@@ -1580,7 +1580,7 @@ def some_func(default_arg=[]):
15801580
15811581
**Output:**
15821582
```py
1583-
>>> some_func.__defaults__ #This will show the default argument values for the function
1583+
>>> some_func.__defaults__ # 这里会显示函数的默认参数的值
15841584
([],)
15851585
>>> some_func()
15861586
>>> some_func.__defaults__
@@ -1593,7 +1593,7 @@ def some_func(default_arg=[]):
15931593
(['some_string', 'some_string'],)
15941594
```
15951595
1596-
- 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:
1596+
- 避免可变参数导致的错误的常见做法是将 `None` 指定为参数的默认值, 然后检查是否有值传给对应的参数. 例:
15971597
15981598
```py
15991599
def some_func(default_arg=None):

0 commit comments

Comments
 (0)