Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: functions in a class and memory

If I have a class with several functions:

class Example:

    def func1(self):
        print 'Hi1'
    def func2(self):
        print 'Hi2'
    def func3(self):
        print 'Hi3'

If I create several instances of 'Example', does each instance store its own copies of the functions in the class? Or does Python have a smart way to store the definition only once and look it up every time an instance uses a function in the class?

Also, what about static functions? Does the class keep only one copy of each static function?

like image 426
Squall Leohart Avatar asked Aug 13 '12 17:08

Squall Leohart


People also ask

How are functions stored in memory Python?

Python stores object in heap memory and reference of object in stack. Variables, functions stored in stack and object is stored in heap.

Does class occupy memory in Python?

A class is composed normally of member variables & methods. When we create instance of a class, memory is allocated for member variables of a class.

Does Python clear memory after function?

If you don't manually free() the memory allocated by malloc() , it will never get freed. Python, in contrast, tracks objects and frees their memory automatically when they're no longer used.

Can a class have functions in Python?

Classes can be created as simply a collection of functions. The functions can be defined within the class exactly the same way that functions are normally created. In order to call these functions we need to call it from the class.


1 Answers

When instantiating a class, no new function objects are created, neither for instance methods nor for static methods. When accessing an instance method via obj.func1, a new wrapper object called a "bound method" is created, which will be only kept as long as needed. The wrapper object is ligh-weight and contains basically a pointer to the underlying function object and the instance (which is passed as self parameter when then function is called).

Note that using staticmethod is almost always a mistake in Python. It owes its existence to a historical mistake. You usually want a module-level function if you think you need a static method.

like image 60
Sven Marnach Avatar answered Nov 10 '22 03:11

Sven Marnach