You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Python supports abstract base classes (ABCs) through the abc module in stdlib. This allows you to mark methods that should be overloaded by child classes as such by using the @abstractmethod decorator.
The advantages of this are the following:
Trying to directly create an object from an ABC raises a TypeError that the class is not meant to be instantiated directly.
Trying to create an object from a class that inherits from an ABC, but does not implement all abstract methods raises the same error.
The previously mentioned errors mean that code will fail soon and fail hard, and not only when somewhere down the line a child class is used that doesn't implement all methods.
Abstract methods can still have an implementation to return some default value as a fallback. In the example below of the AquiferData.isinside method is marked as abstract, and should therefore be explicitly overloaded by Aquifer. However, the Aquifer class can explicitly subscribe to the default implementation to return True. For the inhomogeneities the default behaviour isn't appropriate and can be implemented as necessary. For Element.potinf it doesn't make sense to provide a default implementation, so the abstract version can simply contain pass.
An example where this could be used is AquiferData. By changing this:
Python supports abstract base classes (ABCs) through the
abc
module in stdlib. This allows you to mark methods that should be overloaded by child classes as such by using the@abstractmethod
decorator.The advantages of this are the following:
TypeError
that the class is not meant to be instantiated directly.AquiferData.isinside
method is marked as abstract, and should therefore be explicitly overloaded byAquifer
. However, theAquifer
class can explicitly subscribe to the default implementation to return True. For the inhomogeneities the default behaviour isn't appropriate and can be implemented as necessary. ForElement.potinf
it doesn't make sense to provide a default implementation, so the abstract version can simply containpass
.An example where this could be used is
AquiferData
. By changing this:to
you get the same principle, but stricter enforcement.
As an example how these classes work:
produces this output:
The text was updated successfully, but these errors were encountered: