[Tutor] class methods as static methods?

Steven D'Aprano steve at pearwood.info
Sun May 30 04:04:05 CEST 2010


On Sun, 30 May 2010 05:49:45 am Alex Hall wrote:
> Hi all,
> In Battleship, I have a weapons.py file, currently with just one
> missile type (a Harpoon anti-ship missile). This Harpoon class
> defines a getImpactCoords method, which returns all coordinates on
> the map that it will hit. I would like to not instantiate a Harpoon 
> object, just call the Harpoon's getImpactCoords method and pass it
> the required arguments.

I don't understand the logic here. Surely the impact coordinates depends 
on the individual missile (an instance)?


> Is this possible? Thanks. Sorry if I got the
> terms backwards in the subject; I can never remember which is static
> and which is non-static.


In Python terminology, a static method is an ordinary function that is 
called as a method from either a class or a class instance:

class C(object):
    @staticmethod
    def method(x):
        return "Called with argument %s", % x

Note that the method does not receive an automatic instance argument 
(usually called self) when you call it.

A class method is like an ordinary method, except instead of receiving 
the instance (self) as the first argument, it receives the class 
(usually called cls):

class C(object):
    @classmethod
    def method(cls, x):
        return "Called from class %s with argument %s", % (cls, x)

The method always receives the class, regardless of whether you call it 
from the class using C.method(x) or from an instance C().method(x).

You might also be interested in what I call "dualmethod", which passes 
the class as first argument if you call it from the class, and the 
instance if you call it from the instance:

http://code.activestate.com/recipes/577030-dualmethod-descriptor/




-- 
Steven D'Aprano


More information about the Tutor mailing list