[Tutor] class methods as static methods?

Lie Ryan lie.1296 at gmail.com
Sun May 30 00:32:13 CEST 2010


On 05/30/10 05:49, 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. 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.
> 

Yes you can make it a static method or class method:

class Harpoon(object):
    @staticmethod
    def inst(a, b, c):
        print a, b, c
    @classmethod
    def cmeth(cls, a, b, c):
        print cls
        print a, b, c

Harpoon.inst(1, 2, 3)
Harpoon.cmeth(1, 2, 3)

the question is, why would you want to? getImpactCoords() doesn't seem
to be a function that makes sense without a missile instance (I may be
mistaken).



More information about the Tutor mailing list