Python __init___: Is it against conventions?

I am just learning python and I donโ€™t know exactly what should be in __init__ . Usually I just see people writing self.arg = arg for each argument.

I just want to make sure I'm good at coding. Everything is fine 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 this is that I need to call a couple of functions to initialize these values. I am not sure why, but it seemed to me wrong, and I did not see such examples, so I wanted to check whether this is good or not. If not, what can I do instead?

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

+4
source share
3 answers

I would say that I agree that a good style code assigns all instance variables in __init__ due to readability, i.e. anyone who looks at the code (even after a couple of months) should not have to read the entire implementation of the class in order to have an understanding of the objects of variables and instances of this class.

In addition, I renamed the initialize_vars method to _initialize_vars to clear it, which is an internal method that is not expected to be used by class users.

To populate the above information, check out PEP8 :

  • single_leading_underscore: weak indicator of "internal use".
+3
source

This is against the conventions. If you start listing your variables, you should use a list! And yes, it is evil to introduce new instance variables elsewhere than __init__ .

+3
source

I would like initialize_vars to return variables, for example:

 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 be more appropriate to put the contents of initialize_vars inside init , right? unless init has a lot of other logic, and you don't want it to get too big.

+1
source

Source: https://habr.com/ru/post/1391325/


All Articles