Why is a method of a Python class declared without "self" and without decorators not raising an exception?

In Python 2, functions defined in a class body are automatically converted to "unbound methods", and cannot be called directly without a staticmethod decorator. In Python 3, this concept was removed; MyClass.text_method is a simple function that lives inside the MyClass namespace, and can be called directly.

The main reason to still use staticmethod in Python 3 is if you also want to call the method on an instance. If you don't use the decorator, the method will always be passed the instance as the first parameter, causing a TypeError.


There is nothing special about this. In python 3 there is no difference between a function defined inside a class or a function defined outside a class. Both of them are normal functions.

The self that you are talking about here or maybe cls comes into picture only when you access the function through an instance. Hence here you didn't get any error.

However if you modify your code just a little bit to look like the following, then you'd get an error that you expected.

def main(args):
    MyClass().test_method(args)
    # Should throw an error

EDIT:

  • @staticmethod will work on both class instances like MyClass().test_method(args)and just a regular direct call like MyClass.test_method(args)
  • However a regular method(without self in it) can't be called on a class instance. So you will always have to call it as MyClass.test_method(args)