I have an abstract class, Model
, with a few abstract methods, what should I put in the body of the methods?
A return
class Model(metaclass=ABCMeta):
@abstractmethod
def foo(self):
return
A pass
class Model(metaclass=ABCMeta):
@abstractmethod
def foo(self):
pass
Raising a descriptive error
class Model(metaclass=ABCMeta):
@abstractmethod
def foo(self):
raise NotImplementedError("Class {class_name} doesn't implement {func_name} function"
.format(class_name=self.__class__.__name__, func_name=self.foo.__name__))
Typically I would implement method 3 and raise an error, however it looks like it would be redundant, as Python raises an error for me:
>>> bar = module.Model()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: Can't instantiate abstract class Model with abstract methods foo
Between the options presented, which is best practice? Or is there another way I should handle this?
In next Program, we create Myclass as an abstract super class with an abstract method calculate(). This method does not have any body within it. The way to create an abstract class is to derive it from a meta class ABC that belongs to abc (abstract base class) module as: class Abstractclass(ABC):
Last modified: 01 Feb 2022. Abstract classes are classes that contain one or more abstract methods. An abstract method is a method that is declared, but contains no implementation. Abstract classes cannot be instantiated, and require subclasses to provide implementations for the abstract methods.
A class that has a metaclass derived from ABCMeta cannot be instantiated unless all of its abstract methods and properties are overridden. The abstract methods can be called using any of the normal 'super' call mechanisms. abstractmethod() may be used to declare abstract methods for properties and descriptors.
If you run into the NotImplementedError, the recommended way to handle it is to implement the abstract method for which the error is being raised. Because the NotImplementedError is user-defined, Python can't raise this error on its own. So, you'll need to raise it by a package you're using or code your team wrote.
The best thing to put in the body of an abstractmethod
(or abstractproperty
) would be a docstring.
Then you don't need pass
or return
or ...
because a return None
is implicitly included - and a docstring makes this construct "compile" without a SyntaxError
:
from abc import abstractmethod, ABCMeta
class Model(metaclass=ABCMeta):
@abstractmethod
def foo(self):
"""This method should implement how to foo the model."""
The docstring should then explain what should be implemented here so that subclassers know what is/was intended.
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