Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What happens when you initialize instance variables outside of __init__

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.

like image 400
LetsPlayYahtzee Avatar asked Aug 03 '17 13:08

LetsPlayYahtzee


People also ask

Can I initialize instance variables outside constructor?

If you know what value a final variable will have at declaration, it makes sense to initialize it outside the constructors. However, if you want the users of your class to initialize the final variable through a constructor, delay the initialization until the constructor. Save this answer.

Should all member variables be initialized in __ init __?

As a general rule, it is best to initialize all of the instance variables in the __init__() function for consistency. __init__() is what defines instance variables.

Can we use instance variable outside the class?

What is instance variable in Java? Instance variables in Java are non-static variables which are defined in a class outside any method, constructor or a block.

Can instance variables be used without initialization?

An instance variable does not compulsory need to be initialized. Instance variables are accessible inside the same class that declares them.


2 Answers

The __init__ method is not special. The only thing that makes __init__ interesting is the fact that it gets called when you call MyClass().

The following are equivalent:

# Set inside __init__
class MyClassA:
    def __init__(self):
        self.x = 0
obj = MyClassA()

# Set inside other method
class MyClassB:
    def my_initialize(self):
        self.x = 0
obj = MyClassB()
obj.my_initialize()

# Set from outside any method, no self
class MyClassC:
    pass
obj = MyClassC()
obj.x = 0

What makes an instance variable is when you assign it, and that can happen anywhere. Also note that self is not special either, it's just an ordinary function parameter (and in fact, you can name it something other than self).

so that the memory is properly reserved for this variable per instance.

You do not need to "reserve memory" in Python. With ordinary object instances, when you assign self.x = 0 or obj.x = 0, it is kind of like putting a value in a dictionary. In fact,

# This is sometimes equivalent, depending on how obj is defined
obj.__dict__['x'] = 0
like image 83
Dietrich Epp Avatar answered Oct 18 '22 04:10

Dietrich Epp


This has nothing to do with "reserving memory". Python is not C; you should absolutely not think in terms of memory allocation when writing Python.

As a dynamic language, Python behaves in exactly the same way wherever you set an attribute, and __init__ is not in any way privileged when it comes to creating attributes.

The main reason for doing it there, though, is that it then gives your class a consistent interface. If you don't assign at least a placeholder when creating an instance, any code that accesses that attribute needs to check whether or not it even exists first.

That said, there are still plenty of use cases where dynamically annotating an attribute is useful and perfectly acceptable.

like image 44
Daniel Roseman Avatar answered Oct 18 '22 04:10

Daniel Roseman