1

My question is around how the functions stored or executed in memory.

Coming from C++/Java here is my understanding (correct me if am wrong): class definitions and functions inside them are just instructions stored in the code section of the process/thread when the program is in memory. When a class is instantiated only member variables(non-static) will be having memory allocated separately in heap. i.e each object of class will have only instance variables and not function instructions. When a class function is executed via multiple objects it is executed through same location where the function is stored(i.e code section).

Now coming to python: Here functions are treated like objects. Which would mean functions are stored separately in heap and not in code section of the thread/process. And each object of the class will have its own copy of functions along with instance variables.

is my understanding correct? if it is correct what is use of having functions stored in every object?

trincot
  • 317,000
  • 35
  • 244
  • 286
  • see this answer: it explains why function are objects in a heap: https://stackoverflow.com/questions/45746494/functions-as-objects-in-python-what-exactly-is-stored-in-memory – MEdwin Jan 03 '20 at 09:37
  • thanks. This thread explains how functions are stored. But it doesn't seem to explain much on the reason behind it. I cant seem to understand what is need to have of same instructions stored each object. Doesn't that make python less efficient? – Ravish Mallya Jan 03 '20 at 10:06
  • "And each object of the class will have its own copy of functions along with instance variables." - what? No. That conclusion does not follow from the premises. – user2357112 May 11 '20 at 01:39
  • i read this post: https://stackoverflow.com/questions/245192/what-are-first-class-objects here it says everything about a function is an object. To elaborate my doubt a bit more: In this post: https://icarus.cs.weber.edu/~dab/cs1410/textbook/4.Pointers/memory.html it says code/machine instructions lies in specific section of a process. If a function can be passed in as a parameter to another function, does code also go as a parameter then? if it does doesnt it break usual paradigm of a process? If we are passing text implicility as objects get allocated dont they consume additional space? – Ravish Mallya Feb 05 '22 at 16:13

0 Answers0