Static Methods in Python

K

Kris

Hi,
I am a newbie to Python. With a background in Java, I was attempting
to write static methods in the class without the self as the first
parameter, when I got an error. I did a search for the same on Google
and found out that there was no consistent approach to this. I would
like to know what is the prescribed approach for the same. Any
thoughts, pointers about the same would be very much appreciated.

Thanks,
Kris
 
E

Erik Max Francis

Kris said:
I am a newbie to Python. With a background in Java, I was attempting
to write static methods in the class without the self as the first
parameter, when I got an error. I did a search for the same on Google
and found out that there was no consistent approach to this. I would
like to know what is the prescribed approach for the same. Any
thoughts, pointers about the same would be very much appreciated.

Do something like (2.4):

@staticmethod
def aStaticMethod(x, y, z):
...

Prior to 2.4, use:

def aStaticMethod(x, y, z):
...
aStaticMethod = staticmethod(aStaticMethod)
 
J

John Roth

Kris said:
Hi,
I am a newbie to Python. With a background in Java, I was attempting
to write static methods in the class without the self as the first
parameter, when I got an error. I did a search for the same on Google
and found out that there was no consistent approach to this. I would
like to know what is the prescribed approach for the same. Any
thoughts, pointers about the same would be very much appreciated.

Generally, there's very little need for static methods in Python. That
niche is better handled by module level functions. You can use real
static methods with new style classes, using the staticmethod built
in function. However, you can't reference class variables with
static methods - you should use class methods to do that. See the
Python library documentation.

John Roth
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,766
Messages
2,569,569
Members
45,042
Latest member
icassiem

Latest Threads

Top