Translating some Java to Python

Ant antroy at gmail.com
Mon May 21 05:13:34 EDT 2007


On May 20, 9:24 pm, Daniel Gee <zef... at gmail.com> wrote:
...
> The Java version has static methods for common roll styles (XdY and XdY
> +Z) for classes that just want a result but don't want to bother
> keeping an object around for later.
>
> So the question is, assuming that I wanted to keep the static method
> behavior (which I'm not really sure I do), how does one format the
> method header on a 'static' method in Python? Is it just something
> like:
>
> class Foo:
>   def statAdd(self,a):
>     return a+5
>
> or do you drop the 'self' bit and just use a 1 variable parameter list?

Herman has shown you *how* to do static methods in Python, but
typically they are not used. Since Python has first class functions,
and they can be defined at the module level, there is no need to use
static methods.

There is a distinction in Python not present in Java between class and
static methods, class methods get the class passed in as the first
parameter, and can be useful if you want a function that acts on data
that the class provides. Static methods in Python are merely normal
functions that are associated with the class - for conceptual reasons
rather than practical ones, and are rarely used as far as I can tell.
I've certainly never bothered with them.

In the case of your statAdd above, self is never used in the method
body, and so this is a clear indication that a module level function
would be more appropriate.

--
Ant...

http://antroy.blogspot.com/





More information about the Python-list mailing list