Search code examples
pythonpython-3.xpython-2.7class-method

Calling instance method from class method, allowed in python3, disallowed in python 2?


The following code snippet gives error in python2 but no error with python3

class Steps(object):
    def step(self, msg="Default"):
        if not hasattr(self, "funky_attr"):
            print('No attr')
        print(self)
        print(msg)

class FirstTest(Steps):
    @classmethod
    def test_setup(cls):
      cls.step("This is the message")

if __name__ == '__main__':
    C = FirstTest()
    C.test_setup()

With python 2 it produces the error:

TypeError: unbound method step() must be called with CifsTest instance as first argument (got str instance instead)

While with python 3 it runs fine:

No attr

This is the message # Note here the 'self' is the str

Default

Is this the correct behavior ?

Python3 allows calling instance method from class methods ?


Solution

  • In Python 3 methods are regular function objects (not "unbound method" instances) and therefore they do not check that the first argument is an instance of the class.

    Not sure why this change was considered important (uniformity or performance, probably) but what you observed looks like an unwanted side effect of this choice.