Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Abstract methods in Python

Tags:

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?

like image 959
deamon Avatar asked May 02 '11 12:05

deamon


People also ask

What are abstract methods Python?

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.

Why we use abstract method in Python?

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.

How do you create an abstract method in Python example?

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.

Does Python support abstract methods?

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.


1 Answers

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.

like image 54
Sven Marnach Avatar answered Sep 28 '22 17:09

Sven Marnach