-
Notifications
You must be signed in to change notification settings - Fork 6
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
describe lists as default values #36
Changes from 3 commits
3c2b0c5
7712f52
03de790
3cb4e12
361b7df
d5a7a90
07a0ad9
85b9826
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
Original file line number | Diff line number | Diff line change | ||||
---|---|---|---|---|---|---|
|
@@ -521,6 +521,102 @@ Happy Birthday, Mark | |||||
|
||||||
Это один из общепринятых способов написания [docstring](https://www.python.org/dev/peps/pep-0257/) — документации по функции. | ||||||
|
||||||
### Списки как значения по умолчанию | ||||||
|
||||||
Рассмотрим следующую функцию: | ||||||
|
||||||
```python linenums="1" | ||||||
def fn(ls=[1]): | ||||||
ls.append(2) | ||||||
return ls | ||||||
|
||||||
print(fn()) | ||||||
print(fn()) | ||||||
``` | ||||||
|
||||||
``` | ||||||
[1, 2] | ||||||
[1, 2, 2] | ||||||
``` | ||||||
|
||||||
Второй вызов функции привел к результату, отличающемуся от первого вызова. Почему так произошло? Значение `ls` по умолчанию мы объявили равным `[1]`. Оба вызова используют значение по умолчанию. Но при втором вызове в данном случае произошло обращение к тому же списку, который был создан в качестве значения по умолчанию при первом вызове. Как это можно проверить? | ||||||
|
||||||
В Python определена встроенная функция [id](https://docs.python.org/3/library/functions.html#id). Она возвращает целочисленный идентификатор объекта (уникальный и постоянный, пока объект существует). Используем ее, чтобы посмотреть идентификаторы списков. | ||||||
|
||||||
```python linenums="1" | ||||||
def fn_with_id(ls=[1]): | ||||||
print(id(ls)) | ||||||
ls.append(2) | ||||||
return ls | ||||||
|
||||||
print(fn_with_id()) | ||||||
print(fn_with_id()) | ||||||
print(fn_with_id([3])) | ||||||
print(fn_with_id()) | ||||||
``` | ||||||
|
||||||
``` | ||||||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
Suggested change
|
||||||
123928376604123 | ||||||
[1, 2] | ||||||
123928376604123 | ||||||
[1, 2, 2] | ||||||
113928976643254 | ||||||
[3, 2] | ||||||
123928376604123 | ||||||
[1, 2, 2, 2] | ||||||
``` | ||||||
|
||||||
Значения идентификаторов у вас могут быть другие. Важно, что в первом, втором и четвертом вызове эти значения одинаковы и отличаются от третьего вызова, у которого значения списка по умолчанию не используется. Такое поведение сохраняется и для пустого списка как значения по умолчанию, и для непустого, как в примере выше. | ||||||
ch3rn0v marked this conversation as resolved.
Show resolved
Hide resolved
|
||||||
|
||||||
Одним из решений может быть следующее: | ||||||
|
||||||
```python linenums="1" | ||||||
def fixed_fn(ls=None): | ||||||
if ls is None: | ||||||
return [2] | ||||||
|
||||||
ls.append(2) | ||||||
return ls | ||||||
|
||||||
print(fixed_fn()) | ||||||
print(fixed_fn()) | ||||||
print(fixed_fn([1])) | ||||||
print(fixed_fn()) | ||||||
``` | ||||||
|
||||||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. аналогично убрать пустую строку |
||||||
``` | ||||||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
Suggested change
|
||||||
[2] | ||||||
[2] | ||||||
[1, 2] | ||||||
[2] | ||||||
``` | ||||||
|
||||||
Обратите внимание, что с `set`-ом ситуация другая. | ||||||
|
||||||
```python linenums="1" | ||||||
def fn_with_set(_set=set()): | ||||||
_set.add(2) | ||||||
print(id(_set)) | ||||||
return _set | ||||||
|
||||||
print(fn_with_set()) | ||||||
print(fn_with_set()) | ||||||
print(fn_with_set({3})) | ||||||
print(fn_with_set()) | ||||||
``` | ||||||
|
||||||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. убрать пустоту |
||||||
``` | ||||||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
Suggested change
|
||||||
140214028693696 | ||||||
{2} | ||||||
140214028693696 | ||||||
{2} | ||||||
129928985405920 | ||||||
{2, 3} | ||||||
140214028693696 | ||||||
{2} | ||||||
``` | ||||||
|
||||||
vvssttkk marked this conversation as resolved.
Show resolved
Hide resolved
|
||||||
|
||||||
## Анонимные функции | ||||||
|
||||||
Функции, определенные при помощи `def`, имеют название, по которому их можно вызвать, но также существуют и анонимные или неименованные функции. Такие функции могут быть определены при помощи оператора `lambda`. Он позволяет задать входные и выходные данные. Самостоятельно можете почитать [документацию](https://docs.python.org/3/reference/expressions.html#grammar-token-lambda-expr). | ||||||
|
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Между python и bash везде нужно убрать пустую строку