In Python, how do I indicate I'm overriding a method?

前端 未结 10 1875
长情又很酷
长情又很酷 2020-11-29 15:43

In Java, for example, the @Override annotation not only provides compile-time checking of an override but makes for excellent self-documenting code.

I\

10条回答
  •  佛祖请我去吃肉
    2020-11-29 16:44

    In Python 2.6+ and Python 3.2+ you can do it (Actually simulate it, Python doesn't support function overloading and child class automatically overrides parent's method). We can use Decorators for this. But first, note that Python's @decorators and Java's @Annotations are totally different things. The prior one is a wrapper with concrete code while later one is a flag to compiler.

    For this, first do pip install multipledispatch

    from multipledispatch import dispatch as Override
    # using alias 'Override' just to give you some feel :)
    
    class A:
        def foo(self):
            print('foo in A')
    
        # More methods here
    
    
    class B(A):
        @Override()
        def foo(self):
            print('foo in B')
        
        @Override(int)
        def foo(self,a):
            print('foo in B; arg =',a)
            
        @Override(str,float)
        def foo(self,a,b):
            print('foo in B; arg =',(a,b))
            
    a=A()
    b=B()
    a.foo()
    b.foo()
    b.foo(4)
    b.foo('Wheee',3.14)
    

    output:

    foo in A
    foo in B
    foo in B; arg = 4
    foo in B; arg = ('Wheee', 3.14)
    

    Note that you must have to use decorator here with parenthesis

    One thing to remember is that since Python doesn't have function overloading directly, so even if Class B don't inherit from Class A but needs all those foos than also you need to use @Override (though using alias 'Overload' will look better in that case)

提交回复
热议问题