Reputation: 4941
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
self.initialize_vars()
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__
?
Upvotes: 4
Views: 176
Reputation: 40414
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.
Upvotes: 3
Reputation: 17203
I would have initialize_vars return the variables if possible, such as:
def __init__(self, arg1):
self.arg1 = arg1
self.var1,self.var2,self.var3,self.var4,self.var5,self.var6=self.initialize_vars()
def initialize_vars(self):
a=1
b=a*3
#balh blah
return(a,b,3,4,5,6)
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.
Upvotes: 1
Reputation: 3443
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__
.
Upvotes: 2