Search code examples
pythonfunctionmemoryinstances

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?


Solution

  • 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.