I've been using abstract classes in Python with ABCMeta
. When you write an abstract method you tag it with the decorator @abstractmethod
. One thing that I found odd (and unlike other languages) is that when the subclass overrides the superclass method, no decorator like @override
is provided. Does anyone know what the logic behind this might be?
This makes it slightly confusing for someone reading the code to quickly establish which methods override/implement abstract methods versus methods that only exist in the subclass.
In Python method overriding occurs by simply defining in the child class a method with the same name of a method in the parent class. When you define a method in the object you make this latter able to satisfy that method call, so the implementations of its ancestors do not come in play.
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.
Needless to say, Python's decorators are incredibly useful. Not only can they be used to slow down the time it takes to write some code, but they can also be incredibly helpful at speeding up code. Not only are decorators incredibly useful when you find them about, but it is also a great idea to write your own.
The problem with trying to add @override
is that at method definition time, the decorator has no way to tell whether or not the method actually overrides another method. It doesn't have access to the parent classes (or the current class, which doesn't even exist yet!).
If you want to add @override
, the @override
decorator can't actually do any override checking. You then have two options. Either there is no override checking, in which case @override
is no better than a comment, or the type
constructor needs to specifically know about @override
and check it at class creation time. A convenience feature like @override
really shouldn't need to complicate core parts of the type system implementation like that. Also, if you accidentally put @override
on a non-method, the bug will go undetected until you try to call the decorated function and get a weird TypeError.
You're confusing Python decorators with Java annotations. Despite the similar syntax, they are completely different things. A Java annotation is an instruction to the compiler. But a Python decorator is executable code that does something concrete: it wraps the function in another function which can change what it does. This is the case for abstractmethod just as much as any other decorator; it does something, namely tell the ABC that there is a method that needs overriding.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With