-1

In superclass in Python, how can I call the function that's overridden in its subclass?

class A:
    @staticmethod
    def interfaceBasedMethod():
        print "Want to delegate to overriding method in subclass"

    @staticmethod
    def a():
        interfaceBasedMethod() # <-- I know this causes error. But here 
                               # I want to call the overridden method in subclass.

class B(A):
    @staticmethod
    def interfaceBasedMethod():
        print "Class B processes."

if __name__ == "__main__":
    b=B
    b.a()

Ideal output:

Class B processes.

Google search doesn't really return pages about Interface-Based Programming in Python, although it should be common in Java etc. Thanks!

IsaacS
  • 3,551
  • 6
  • 39
  • 61

2 Answers2

2

Putting aside questions of style, use classmethod not staticmethod. It passes in the class which is being used.

class A:
    @classmethod
    def interfaceBasedMethod(cls):
        print "Want to delegate to overriding method in subclass"

    @classmethod
    def a(cls):
        cls.interfaceBasedMethod()

class B(A):
    @classmethod
    def interfaceBasedMethod(cls):
        print "Class B processes."

if __name__ == "__main__":
    b=B
    b.a()
benpmorgan
  • 604
  • 3
  • 9
1

Your inheritance question was answered before here.

But in summary, Python provides a function super(type[, instance]).

Documented here, super provides a fairly clean way for accessing superclass methods from within a subclass. This page provides an exhaustive study of super() use cases, but this is the run-down.

class C(B):
    def method(self, arg):
        super(C, self).method(arg)

Which could be generalized a bit....

class C(B):
    def method(self, arg):
        super(self.__class__, self).method(arg)
Community
  • 1
  • 1
arrdem
  • 2,365
  • 1
  • 16
  • 18