How could I implement a virtual method and override it in python?

Steve D'Aprano steve+python at pearwood.info
Wed Sep 14 20:58:07 EDT 2016


On Thu, 15 Sep 2016 08:16 am, wesley.keeling at iugome.com wrote:

> Hey guys, I will show the code first:
> 
> Helper.py:
> 
> def Foo( *args ):
> print ("This is a callback")
> 
> def Run:
>     Foo()
> 
> 
> MyModule.py:
> 
> import Helper
> 
> def Foo( *args ):
> print ("I want to be the new callback")
> 
> 
> 
> I want to be able to call the Foo method in MyModule.py when it's there
> first and when it's not I want to call the Foo in helper.py.

What is doing the calling?

Surely MyModule knows whether or not it has a Foo function? Or rather, the
author of MyModule knows whether or not he has defined a Foo function.

I don't understand how this problem would come about in practice. If you are
writing MyModule, you surely must know whether or not you have defined Foo.
If you have, you call

    Foo()


and if you haven't, you write:

    from Helper import Foo
    Foo()

or perhaps:

    import Helper
    Helper.Foo()


If for some reason you won't know until runtime whether or not Foo exists,
you can say:


    try:
        Foo  # don't call the function, just name it
    except NameError:
        # Doesn't exist, so use the helper function
        from Helper import Foo
    
    Foo()  # works either way now



If it is a *third* module doing the calling, then things start to be a bit
more clear. So I have my main application, and I want to use a function Foo
defined in MyModule, if it exists, otherwise Foo defined in Helper.

Here is one way to do it:


    # main.py
    try:
        from MyModule import Foo
    except ImportError:
        from Helper import Foo
    
    Foo()




> I am coming from .net so I am not fully understanding how the Foo method
> would override the other one.

It doesn't.

Perhaps you are unclear about the difference between methods of a class and
functions in modules?




-- 
Steve
“Cheer up,” they said, “things could be worse.” So I cheered up, and sure
enough, things got worse.




More information about the Python-list mailing list