Dannyboy
Dannyboy

Reputation: 2052

python using __init__ vs just defining variables in class - any difference?

I'm new to Python - and just trying to better understand the logic behind certain things.

Why would I write this way (default variables are in __init__):

class Dawg:


    def __init__(self):
        self.previousWord = ""
        self.root = DawgNode()
        self.uncheckedNodes = []
        self.minimizedNodes = {}

    def insert( self, word ):
        #...

    def finish( self ):
        #...

Instead of this:

class Dawg:
    previousWord = ""
    root = DawgNode()
    uncheckedNodes = []
    minimizedNodes = {}

    def insert( self, word ):
        #...

    def finish( self ):
        #...

I mean - why do I need to use __init__ -> if I can just as easily add default variables to a class directly?

Upvotes: 20

Views: 6211

Answers (2)

Óscar López
Óscar López

Reputation: 235984

When you write this:

class Dawg:
    previousWord = ""
    root = DawgNode()
    uncheckedNodes = []
    minimizedNodes = {}

Those are not instance variables, they're class variables (meaning: the same variables with the same values are shared between all instances of the class.) On the other hand, this:

class Dawg:
    def __init__(self):
        self.previousWord = ""
        self.root = DawgNode()
        self.uncheckedNodes = []
        self.minimizedNodes = {}

... Is declaring instance variables, meaning: the values are different for each instance of the class. As you see, each snippet means a completely different thing, and you have to pick the one that is appropriate for you. Hint: most of the time you're interested in instance variables, because class variables define a kind of shared global state for your objects, which is error prone.

Upvotes: 4

thefourtheye
thefourtheye

Reputation: 239443

When you create variables in the Class, then they are Class variables (They are common to all the objects of the class), when you initialize the variables in __init__ with self.variable_name = value then they are created per instance and called instance variables.

For example,

class TestClass(object):
    variable = 1

var_1, var_2 = TestClass(), TestClass()
print var_1.variable is var_2.variable
# True
print TestClass.variable is var_1.variable
# True

Since variable is a class variable, the is operator evaluates to True. But, in case of instance variables,

class TestClass(object):
    def __init__(self, value):
        self.variable = value

var_1, var_2 = TestClass(1), TestClass(2)
print var_1.variable is var_2.variable
# False
print TestClass.variable is var_1.variable
# AttributeError: type object 'TestClass' has no attribute 'variable'

And you cannot access an instance variable, with just the class name.

Upvotes: 29

Related Questions