In python when you initialize an instance variable (e.g. self.my_var
) you should do it in your class __init__
function, so that the memory is properly reserved for this variable per instance (<--my mistake, see bellow). When you want to define class level variables you do it outside of a function and without the self
prefix.
What happens when you instantiate a variable inside a function other than the __init__
with the self
prefix? It behaves like a normal instance variable, is there a compelling reason to not do it? other than the danger of making code logic implicit, which is enough of a reason already, but I am wondering are you potentially running on memory or other hidden issues if you do so?
I couldn't not find that discussed somewhere.
update sorry
I misinterpreted some answers including the first and the third here Python __init__ and self what do they do? (looking for the others)
and thought that __init__
is some special type of function, thinking that it somehow has memory allocation functionality (!?). Wrong question.
__init__
, since it makes it easier for readers to know what attributes your class has. But if you can't initialise those attributes to sensible values it may be better for your code to fail noisily rather than to do the wrong thing with some "placeholder" initial value likeNone
or some other false-ish value. – Adkinson__init__
is a special method; the double underscores at the start and end of the name indicate that it's special. And it is special in that it gets called automatically to perform initialization of the fresh instance returned by__new__
. But ultimately it's only a convention that we use it to initialize the instance's attributes, any method is permitted to do that, and as the answers below show, it's also perfectly legal to add instance attributes via code outside the class definition. – Adkinson