The difference between the two is that in the above example you are creating a class attribute, while in the init you are creating an instance attribute. The difference between the two is this:
class Foo():
bob = "my name is bob"
print(Foo.bob)
# outputs "my name is bob"
class Foo():
def __init__(self):
self.bob = "my name is bob"
Doing print(Foo.bob)
:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: type object 'Foo' has no attribute 'bob'
To access bob in the init you have to instantiate:
f = Foo()
print(f.bob)
# outputs "my name is bob"
What further differentiates the two of these implementations is that the class attribute will be shared among all instances, while instance attributes are shared only within your instance.
So, for anything defined inside your __init__
, if you create a new object of Foo, you will not carry any of the changes that you might make to variables inside the init to other instances of Foo.
However, for class attributes, whatever class attribute you change will be changed across all instances of Foo.