I need something like an abstract protected
method in Python (3.2):
class Abstract: def use_concrete_implementation(self): print(self._concrete_method()) def _concrete_method(self): raise NotImplementedError() class Concrete(Abstract): def _concrete_method(self): return 2 * 3
Is it actually useful to define an "abstract" method only to raise a NotImplementedError?
Is it good style to use an underscore for abstract methods, that would be protected
in other languages?
Would an abstract base class (abc) improve anything?
An abstract method is a method that is declared, but contains no implementation. Abstract classes may not be instantiated, and its abstract methods must be implemented by its subclasses.
Its purpose is to define how other classes should look like, i.e. what methods and properties they are expected to have. The methods and properties defined (but not implemented) in an abstract class are called abstract methods and abstract properties.
By using @abstractmethod decorator we can declare a method as an abstract method. @abstractmethod decorator presents in abc module. We should import the abc module in order to use the decorator. Since abstract method is an unimplemented method, we need to put a pass statement, else it will result in error.
An abstract class may or may not include abstract methods. Python doesn't directly support abstract classes. But it does offer a module that allows you to define abstract classes. To define an abstract class, you use the abc (abstract base class) module.
In Python, you usually avoid having such abstract methods alltogether. You define an interface by the documentation, and simply assume the objects that are passed in fulfil that interface ("duck typing").
If you really want to define an abstract base class with abstract methods, this can be done using the abc
module:
from abc import ABCMeta, abstractmethod class Abstract(metaclass=ABCMeta): def use_concrete_implementation(self): print(self._concrete_method()) @abstractmethod def _concrete_method(self): pass class Concrete(Abstract): def _concrete_method(self): return 2 * 3
Again, that is not the usual Python way to do things. One of the main objectives of the abc
module was to introduce a mechanism to overload isinstance()
, but isinstance()
checks are normally avoided in favour of duck typing. Use it if you need it, but not as a general pattern for defining interfaces.
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