Nice programing

i = i + n이 i + = n과 정말 동일합니까?

nicepro 2021. 1. 7. 21:21
반응형

i = i + n이 i + = n과 정말 동일합니까?


한 코드 블록은 작동하지만 다른 블록은 작동하지 않습니다. 두 번째 블록을 제외하고는 이해가 될 것입니다. 그들은 실질적으로 동일한 작업입니다.

l = ['table']
i = []

버전 1

for n in l:
    i += n
print(i)

산출: ['t', 'a', 'b', 'l', 'e']

버전 2

for n in l:
    i = i + n
print(i)

산출:

TypeError : 목록 ( "str"아님) 만 목록에 연결할 수 있습니다.


이 이상한 오류의 원인은 무엇입니까?


동일 할 필요는 없습니다.

은 Using +조작하면 메소드를 호출 __add__사용하는 동안 +=운영자 호출을 __iadd__. 이러한 메서드 중 하나가 호출 될 때 어떤 일이 발생하는지는 전적으로 해당 객체에 달려 있습니다.

당신이 사용하는 경우 x += yx제공하지 않는 __iadd__방법 (또는 메서드가 반환을 NotImplemented), __add__A와 사용되는 대체 그 의미 x = x + y발생합니다.

리스트의 경우, 사용하는 l += iterable사실은 연장리스트 l의 요소를 iterable. 귀하의 경우에는 문자열의 모든 문자 (반복 가능)가 extend작업 중에 추가됩니다 .

데모 1 : 사용 __iadd__

>>> l = []
>>> l += 'table'
>>> l
['t', 'a', 'b', 'l', 'e']

데모 2 : 사용 extend은 동일합니다.

>>> l = []
>>> l.extend('table')
>>> l
['t', 'a', 'b', 'l', 'e']

데모 3 : 목록과 문자열을 추가하면 TypeError.

>>> l = []
>>> l = l + 'table'
[...]
TypeError: can only concatenate list (not "str") to list

사용하지 않음은 +=당신에게 제공 TypeError여기에만 있기 때문에 __iadd__구현하는 확장 동작을.

데모 4 : 일반적인 함정 : +=새 목록을 작성하지 않습니다. is운영자 와 동일한 객체 신원을 확인하여이를 확인할 수 있습니다 .

>>> l = []
>>> l_ref = l # another name for l, no data is copied here
>>> l += [1, 2, 3] # uses __iadd__, mutates l in-place
>>> l is l_ref # confirm that l and l_ref are names for the same object
True
>>> l
[1, 2, 3]
>>> l_ref # mutations are seen across all names
[1, 2, 3]

그러나 l = l + iterable구문은 새 목록을 작성합니다.

>>> l = []
>>> l_ref = l # another name for l, no data is copied here
>>> l = l + [1, 2, 3] # uses __add__, builds new list and reassigns name l
>>> l is l_ref # confirm that l and l_ref are names for different objects
False
>>> l
[1, 2, 3]
>>> l_ref
[]

경우에 따라 원본 목록을 += 변경 하고 목록
l = l + iterable작성 하고 이름을 다시 할당 하기 때문에 미묘한 버그가 발생할 수 있습니다 .l

보너스

문서에서 이것을 찾기위한 Ned Batchelder의 도전


아니.

7.2.1. 증강 할당 문 :

An augmented assignment expression like x += 1 can be rewritten as x = x + 1 to achieve a similar, but not exactly equal effect. In the augmented version, x is only evaluated once. Also, when possible, the actual operation is performed in-place, meaning that rather than creating a new object and assigning that to the target, the old object is modified instead.


If in the second case, you wrap a list around n to avoid errors:

for n in l:
    i = i + [n]
print(i)

you get

['table']

So they are different operations.

ReferenceURL : https://stackoverflow.com/questions/52747784/is-i-i-n-truly-the-same-as-i-n

반응형