1

Can some one explain on the way Python manages memory management during creation of an object in class.

For example in java we can only declare member variables and the initialisation part happens inside the constructor. That means memory used when an object is constructed.

But in python we can initialise a class variable outside the init method. Where is this data stored?

Sabyasachi
  • 1,484
  • 12
  • 20
  • It's a little unclear what you're referring to. Could you provide some small code examples of the behavior you want explained? – Patrick Haugh Jul 12 '18 at 02:30
  • 1
    [A Beginner's Guide to Python's Namespaces, Scope Resolution, and the LEGB Rule](https://sebastianraschka.com/Articles/2014_python_scope_and_namespaces.html) – Elliott Frisch Jul 12 '18 at 02:34
  • class variables are stored in the classes namespace, `MyClass.__dict__` or `vars(MyClass)`. Instance variables are stores in the instance's namespace: `my_instance = MyClass()` then `my_instance.__dict__` or `vars(my_instance)`. Variables exist when they are assigned to, and doesn't have variable declarations. – juanpa.arrivillaga Jul 12 '18 at 02:39

1 Answers1

0

As a precursor, this question has already been answered here, this may also be a good reference. However, I will try to explain it again. The init method in Python is designed for conventional use and although a special method in the fact that it is reserved to go at the beginning of a method it is not required. Memory management in Python involves a private heap containing all Python objects and data structures. If you were to initialize a class variable outside the init method declaration, it would simply be stored in the heap along with those initialized in the init method. Hope this helps!