I am fairly new to python, and noticed these posts: Python __init__ and self what do they do? and Python Classes without using def __init__(self)
After playing around w
As others have stated, it's the difference between a variable on a class and a variable on a class instance. See the following example.
>>> class A:
... a = []
...
>>> class B:
... def __init__(self):
... self.b = []
...
>>> a1 = A()
>>> a1.a.append('hello')
>>> a2 = A()
>>> a2.a
['hello']
>>> b1 = B()
>>> b1.b.append('goodbye')
>>> b2 = B()
>>> b2.b
[]
For immutable objects like tuples, strings, etc. it's harder to notice the difference, but for mutables, it changes everything—the changes applied are shared between ALL instances of that class.
Note also that the same behavior happens for keyword argument defaults!
>>> class A:
... def __init__(self, a=[]):
... a.append('hello')
... print(a)
...
>>> A()
['hello']
>>> A()
['hello', 'hello']
>>> A()
['hello', 'hello', 'hello']
>>> class B:
... def __init__(self, b=None):
... if b is None:
... b = []
... b.append('goodbye')
... print(b)
...
>>> B()
['goodbye']
>>> B()
['goodbye']
>>> B()
['goodbye']
This behavior bites a lot of new Python programmers. Good for you in discovering these distinctions early on!