0
# 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'
  1. 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?
  2. 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?
jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
gowvia
  • 1
  • 1
  • 1
    Case 1 creates a _class_ attribute, case 2 creates an _instance_ attribute. With an immutable value like a string it's hard to tell the difference, but there is one. Case 3 means you can easily make a mistake and have a "Foo" that lacks the attribute entirely. – jonrsharpe Nov 15 '21 at 10:04
  • In addition to the first comment. You can access `a` in Case 1 without creating an instance of Foo. You can use it like `Foo.a` because its an class attribute – luigigi Nov 15 '21 at 10:07
  • @jonrsharpe can you please elaborate further, maybe in terms of a memory model? – gowvia Nov 15 '21 at 10:07
  • With a mutable value: https://stackoverflow.com/q/1680528/3001761 – jonrsharpe Nov 15 '21 at 10:14
  • 1
    https://www.tutorialsteacher.com/articles/class-attributes-vs-instance-attributes-in-python – Achille G Nov 15 '21 at 10:15

0 Answers0