1

The following code

class Myclass():
    print("from global")
    a = 1

    def __init__(self):
        print("from init")
        self.b = 2

x = Myclass()
print(x.a, x.b)

outputs

from global
from init
(1, 2)

What is the advantage of placing code which is executed when an object is created in __init__ (print("from init") in the example above) instead of directly at the class level (print("from global"))?

WoJ
  • 27,165
  • 48
  • 180
  • 345
  • I've never seen anyone put statements at class level, kinda surprised it works. Placing it in the `__init__` is useful for inheritance, and passing args to it. – MightyPork Jan 05 '15 at 10:21
  • 1
    Because there is such a thing as class-level attributes vs. per-instance attributes. `__init__` lets you access the instance as it is created. – Martijn Pieters Jan 05 '15 at 10:23
  • Wrong flagged duplicate; correct duplicate at http://stackoverflow.com/questions/1537202/variables-inside-and-outside-of-a-class-init-function –  Jan 05 '15 at 10:23
  • @Evert: the other directly addresses this case. It is fine to create a little bit of a chain. – Martijn Pieters Jan 05 '15 at 10:23
  • Hm, then the other isn't an exact duplicate; usual problem with closing questions as duplicate. –  Jan 05 '15 at 10:24
  • Thanks for the answers - as a side note it is interesting that the duplicates (and duplicates of duplicates) did not show up when I was searching. I revived the suggested duplicates but none of them were correct. I guess I should have done an explicit search instead. – WoJ Jan 05 '15 at 10:26

0 Answers0