2

I'm trying to make some kind of static inheritance happen. The code below prints "nope". I'm not sure how to explain myself but what I want is that class A uses B's method if it exists.

class A(object):
    @staticmethod
    def test():
       print("nope")

    @staticmethod
    def test2():
        __class__.test()

class B(A):
    @staticmethod
    def test():
        print("It Works")

    @staticmethod
    def run():
        __class__.test2()


if __name__ == "__main__":
    B.run()
2
  • Then don't use static methods. Use class methods instead. Commented Mar 17, 2014 at 14:28
  • If you are looking for static inheritance, chances are high that you are doing something wrong… Commented Mar 17, 2014 at 14:36

1 Answer 1

6

__class__ as a closure reference was never meant to be used as a reference to the current instance type; it'll always refer to the class you defined a method on (e.g. A for A.test2). It is a internal implementation detail used by the super() function. Don't use it here.

Use @classmethod instead;

class A(object):
    @classmethod
    def test(cls):
       print("nope")

    @classmethod
    def test2(cls):
        cls.test()

class B(A):
    @classmethod
    def test(cls):
        print("It Works")

    @classmethod
    def run(cls):
        cls.test2()


if __name__ == "__main__":
    B.run()
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks a lot! I love this site!

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.