-6

Is this the correct way to imitate a static method in Python? Does Python allow static methods?

class C(object):

    def show(self,message):
        print("The message is: {}".format(message))

m = "Hello World!"
C.show(C,message=m)

The message is: Hello World!

Patt Mehta
  • 4,110
  • 1
  • 23
  • 47

4 Answers4

3

The idiomatic translation of a static method from other languages is usually a module-level method.

def show(message):
    print("The message is: {}".format(message))

The answers telling you that python has @staticmethods are correct, and also misleading: it is usually correct to just use a module-level function.

roippi
  • 25,533
  • 4
  • 48
  • 73
2

You should use @classmethod:

@classmethod
def show(cls, message):
        print("The message is: {}".format(message))

The difference between a classmethod and a staticmethod is that the latter knows nothing about its enclosing class, whereas the former does (via the cls argument). A staticmethod can just as easily be declared outside the class.

If you don't want show() to know anything about C, either use @staticmethod or declare show() outside of C.

arshajii
  • 127,459
  • 24
  • 238
  • 287
2

You should use @staticmethod:

@staticmethod
def show(message):
    print("The message is: {}".format(message))
glglgl
  • 89,107
  • 13
  • 149
  • 217
1

You can use the decorator @classmethod. That won't pose a problem. Additionally

if a class method is called for a derived class, the derived class object is passed as the implied first argument (http://docs.python.org/3.3/library/functions.html#classmethod).

class C1(object):

    @classmethod
    def show(cls,message):
        print("[{}] The message is: {}".format(cls,message))

class C2(C1):
    pass

m = "Hello World!"
C2.show(message=m)
# vs. C1.show(message=m) with output [<class '__main__.C1'>] The message is: Hello World!

[<class '__main__.C2'>] The message is: Hello World!

Patt Mehta
  • 4,110
  • 1
  • 23
  • 47