Fork me on GitHub

Заклинатель змей? Apr 13, 2016

Python имеет очень простой синтаксис, и практически всегда ведёт себя предсказуемо. Однако порой происходит нечто невероятное…

Непредсказуемые списки

x = [[]] * 3
x[0].append('a')
x[1].append('b')
x[2].append('c')
x[0] = ['d']
print x

Результат

>>> x = [[]] * 3
>>> x[0].append('a')
>>> x[1].append('b')
>>> x[2].append('c')
>>> x[0] = ['d']
>>> print x
[['d'], ['a', 'b', 'c'], ['a', 'b', 'c']]

a = ([], )
a[0].extend([1])
a[0] += [2]
print a[0]

Результат

>>> a = ([], )
>>> a[0].extend([1])
>>> a[0] += [2]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'tuple' object does not support item assignment
>>> print a[0]
[1, 2]

# list += str
x = []
x += 'abcd'
print x

# list + str
x = []
x = x + 'abcd'
print x

Результат

>>> # list += str
>>> x = []
>>> x += 'abcd'
>>> print x
['a', 'b', 'c', 'd']
>>>
>>> # list + str
>>> x = []
>>> x = x + 'abcd'
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: can only concatenate list (not "str") to list
>>> print x
[]

ООП, такое ООП

>>> class A():
...   def foo(self):
...     print "this is A"
... 
>>> class B():
...   def foo(self):
...     print "this is B"
... 
>>> 
>>> a = A()
>>> b = B()
>>> 
>>> a.foo()
this is A
>>> b.foo()
this is B
>>> 
>>> A.foo = B.foo
>>> 
>>> a.foo()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unbound method foo() must be called with B instance as first argument (got nothing instead)
>>> 
>>> A.foo = b.foo
>>> a.foo()
this is B
>>>