# case 1
class Foo():
a = 'spam'
>>> x = Foo()
>>> x.a
'spam'
#case 2
class Foo():
def __init__(self):
self.a = 'spam'
>>> y = Foo()
>>> y.a
'spam'
#case 3
class Foo():
pass
>>> z = Foo()
>>> z.a = 'spam'
- All objects that I instantiate based on
Foo
, have the a
attribute in cases 1 and 2. So what's the difference? Why define the attributes within the __init__()
method as in case 2 over case 1. Other than the former more logical and closer-to-reality style of organizing the code (e.g. reasoning that the class
Dog
doesn't have any color
per se, but a particular instance of that Dog
, say scooby
does, so it makes more sense to define the attribute color
within the __init__()
method.), is there any other reason?
- I see the advantage of cases 1 and 2 over case 3. But when would I need to assign an attribute to an object like in case 3?