Take the 2-minute tour ×

I'm just learning python and I'm not sure exactly what's supposed to go in __init__. Normally I just see people writing self.arg = arg for each arg.

I just want to be completely sure I'm coding well. Is it okay if I have something like this:

def __init__(self, arg1):
    self.arg1 = arg1
    self.var1 = 0
    self.var2 = 0
    self.var3 = 0
    self.var4 = 0
    self.var5 = None
    self.var6 = None

The reason for doing this is that I need to call a couple functions to get those values initialized. I'm not sure why but it seemed kind of wrong and I haven't seen any similar examples so I wanted to check if it's okay or not. If not, what might I do instead?

Also, is it bad to introduce self.var7, for example, in another function after __init__?

share|improve this question
add comment

3 Answers

up vote 3 down vote accepted

I'd say that I agree on that good style code assigns all instance variables in __init__ because of readability, that is, anyone who takes a look at the code (even yourself in a couple of months) shouldn't need to read the whole class implementation to have an idea about the variables and instance object of that class could hold.

Aside from that, I'd rename initialize_vars method to _initialize_vars just to make it clear that is an internal method not expected to be used by the users of the class.

To complete the information above, please have a look at PEP8:

  • single_leading_underscore: weak "internal use" indicator.
share|improve this answer
Also you don't want to get "unexpected" NameErrors. –  Gandaro Jan 16 '12 at 20:33
add comment

It is against the conventions. If you start numerating your variables you should use a list! And yes, it is evil to introduce new instance variables somewhere else than __init__.

share|improve this answer
I think the member names are merely (lame) examples and not relevant to the question. –  delnan Jan 16 '12 at 20:31
add comment

I would have initialize_vars return the variables if possible, such as:

def __init__(self, arg1):
    self.arg1 = arg1

def initialize_vars(self):
    #balh blah

However, it would make more sense to put the contents of initialize_vars inside init would it not? unless init is going to have a lot of other logic in it and you don't want it to become too big.

share|improve this answer
add comment

Your Answer


