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 ?

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

3 Comments

Thank you for explaining that. A couple of days ago I need to do this(call instance method from classmethod) when I came across this link stackoverflow.com/questions/16427379/… And it seems, that is not entirely correct
@mittal in that question the answer suggests a change so an instance method will call a class method. (the since it is a instance method part in the explanation applies to __init__())
@tevemadar Yes I could do that but I don't own the code of master class :) But now I know that with python 3 I can just pass anything (even None) and call instance method from classmethod

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.