Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

oop

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?

like image 587
Dannyboy Avatar asked Jul 14 '14 15:07

Dannyboy


1 Answers

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.

like image 141
thefourtheye Avatar answered Sep 18 '22 04:09

thefourtheye