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__?
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_varsmethod to_initialize_varsjust 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: