user1187968
user1187968

Reputation: 7986

Python static method vs. Java static method

In Java, we only store one copy of the static method into memory, and we can call it over and over again. This is for performance and space saving.

Previously, someone had claimed in work that static function in Python does not work the same way as in Java, is this correct?

Someone also claimed that every time we are calling the Python static method, and Python Interpreter still need to spend the time to instantiate an object first. Is this correct?

class A(object):
     @staticmethod
     def static_1():
         print 'i am static'

Upvotes: 3

Views: 1414

Answers (3)

Hayden
Hayden

Reputation: 459

The Python method for java static method is @classmethod.

Upvotes: 4

user2357112
user2357112

Reputation: 280291

Accessing a Python static method does not involve creating a new object. Python just returns the original function object.

(Accessing a non-static method does involve creating a new method object, but this is cheap. In particular, it only bundles together a reference to the function and a reference to self; it does not involve copying the function.)

Upvotes: 1

Vlad
Vlad

Reputation: 9481

There is a difference between Python the language and specific Python implementation.

Also, almost all the languages store only one copy of method each method in memory. This applies to all static, class and regular method. The savings you mentioned come from not needing to pass the pointer to 'self' in Python or 'this' in Java. One less parameter to pass could add to huge savings for the methods that are called from within innermost long running loops.

As for storing methods themselves. Implementations like PyPi constantly perform JIT to compile methods into machine code. They keep recompiling based on updated statistics on how method performs. I believe similar behaviour occurs in Java.

Upvotes: 0

Related Questions