1

The following are test classes with methods not taking in cls or self arguments and dont have @staticmethod decorator. They work like normal static methods without complaining about arguments. This seems contrary to my understanding of python methods. Does python automatically treat non-class, non-instance methods as static?

>>> class Test():
... def testme(s):
...  print(s)
...
>>> Test.testme('hello')
hello

>>> class Test():
...  def testme():
...   print('no')
...
>>> Test.testme()
no

P.S: I am using python3.4

karsep5
  • 72
  • 8
  • See the accepted answer here: http://stackoverflow.com/questions/735975/static-methods-in-python – oopcode May 11 '15 at 10:13

2 Answers2

3

It sort of does, yes. However, note that if you call such an "implicit static method" on an instance, you will get an error:

>>> Test().testme()
Traceback (most recent call last):
  File "<pyshell#2>", line 1, in <module>
    Test().testme()
TypeError: testme() takes 0 positional arguments but 1 was given

This is because the self parameter still gets passed, which doesn't happen with a proper @staticmethod:

>>> class Test:
    @staticmethod
    def testme():
        print('no')


>>> Test.testme()
no
>>> Test().testme()
no
jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
  • 1
    While only indirectly relevant to the question and answer here, there's an interesting [answer](http://stackoverflow.com/a/1669524/660848) on how `@staticmethod` and `@classmethod` behave. – wonderb0lt May 11 '15 at 10:19
2

Note that this doesn't work in Python 2:

>>> class Test(object):
...     def testme():
...         print 'no'
...
>>> Test.testme()
Traceback (most recent call last):
  File "<ipython-input-74-09d78063da08>", line 1, in <module>
    Test.testme()
TypeError: unbound method testme() must be called with Test instance as first argument (got nothing instead)

But in Python 3, unbound methods were removed, as Alex Martelli points out in this answer. So really all you're doing is calling a plain function that happens to be defined inside the Test class.

Community
  • 1
  • 1
Daniel Roseman
  • 588,541
  • 66
  • 880
  • 895