difference between variables inside and outside of __init__()

Teifion picture Teifion · Oct 8, 2009 · Viewed 135.3k times · Source

Is there any difference at all between these classes besides the name?

class WithClass ():
    def __init__(self):
        self.value = "Bob"
    def my_func(self):
        print(self.value)

class WithoutClass ():
    value = "Bob"

    def my_func(self):
        print(self.value)

Does it make any difference if I use or don't use the __init__ method for declaring the variable value?

My main worry is that I'll be using it one way, when that'll cause me further problems down the road.

Answer

S.Lott picture S.Lott · Oct 8, 2009

Variable set outside __init__ belong to the class. They're shared by all instances.

Variables created inside __init__ (and all other method functions) and prefaced with self. belong to the object instance.