Using NotImplementedError instead of abstract classes

MyBase is forcing implementation of method f() in all children. This can be achieved either by using abc.ABCMeta to make f() an abstractmethod:

import abc   class MyBase(metaclass=abc.ABCMeta):     @abc.abstractmethod     def f(self, x):         pass  class Child1(MyBase):     def f(self, x):         print(x)  class Child2(MyBase):     pass  Child1().f(4)   # prints 4 Child2().f(4)   # TypeError: Can't instantiate abstract class Child2 with abstract methods f MyBase()        # TypeError: Can't instantiate abstract class MyBase with abstract methods f 

..or alternatively, by NotImplementedError:

class MyBase():      def f(self, x):         raise NotImplementedError('Abstract method not implemented.')  class Child1(MyBase):     def f(self, x):         print(x)  class Child2(MyBase):     pass  Child1().f(4)   # prints 4 Child2().f(4)   # raises implementation error MyBase()        # does NOT raise error 


Using an abstract class instead of returning NotImplementedError disallows for example accidental instantiation of MyBase().

Are there any other benefits (or drawbacks) from using an abstract class over NotImplementedError?

Replay

You should use an abstract class because it is the appropriate choice for your model, not because of some desired side effect. So instead of thinking benefits, think meaning.

An abstract class classifies classes and allows you to group common data and behavior for that group of classes. If that fits your problem domain (you recognize multiple classes with common properties), use an abstract class. If it does not and you just want to hint an implementor to complete an implementation, create a template or something and throw your exceptions.

Not being able to create an instance of an abstract class is not a "drawback" of the thing, it is inherent to its purpose.

Category: python Time: 2016-07-31 Views: 3

Related post

iOS development

Android development

Python development

JAVA development

Development language

PHP development

Ruby development

search

Front-end development

Database

development tools

Open Platform

Javascript development

.NET development

cloud computing

server

Copyright (C) avrocks.com, All Rights Reserved.

processed in 0.188 (s). 12 q(s)