Search code examples
pythonoopinheritanceclass-methodstatic-functions

How to refer overriden class functions in python


I know C++ and Java and I am unfamiliar with Pythonic programming. So maybe it is bad style what I am trying to do.

Consider fallowing example:

class foo:
        def a():
                __class__.b() # gives: this is foo
                bar.b() # gives: this is bar
                foo.b() # gives: this is foo
                # b() I'd like to get "this is bar" automatically

        def b():
                print("this is foo")

class bar( foo ):
        def b( ):
                print("this is bar")

bar.a()

Notice, that I am not using self parameters as I am not trying to make instances of classes, as there is no need for my task. I am just trying to refer to a function in a way that the function could be overridden.


Solution

  • What you want is for a to be a classmethod.

    class Foo(object):
        @classmethod
        def a(cls):
            Foo.b() # gives: this is foo
            Bar.b() # gives: this is bar
            cls.b() # gives: this is bar
        @staticmethod
        def b():
            print("this is foo")
    
    class Bar(Foo):
        @staticmethod
        def b():
            print("this is bar")
    
    Bar.a()
    

    I've edited your style to match the Python coding style. Use 4 spaces as your indent. Don't put extra spaces in between parenthesis. Capitalize & CamelCase class names.

    A staticmethod is a method on a class that doesn't take any arguments and doesn't act on attributes of the class. A classmethod is a method on a class that gets the class automatically as an attribute.

    Your use of inheritance was fine.