Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between abstract class and interface in Python

What is the difference between abstract class and interface in Python?

like image 670
gizmo Avatar asked Dec 16 '08 17:12

gizmo


People also ask

What is the difference between abstract class and interface?

Abstract Class Vs. Interface: Explore the Difference between Abstract Class and Interface in Java. The Abstract class and Interface both are used to have abstraction. An abstract class contains an abstract keyword on the declaration whereas an Interface is a sketch that is used to implement a class.

What is an interface Python?

In object-oriented languages like Python, the interface is a collection of method signatures that should be provided by the implementing class. Implementing an interface is a way of writing an organized code and achieve abstraction.

What is the difference between abstract class and inheritance in Python?

These are two different concept and selections are based on the requirements. Abstraction hide the implementation details and only show the functionality. It reduce the code complexity. Inheritance create a class using a properties of another class.


1 Answers

What you'll see sometimes is the following:

class Abstract1:     """Some description that tells you it's abstract,     often listing the methods you're expected to supply."""      def aMethod(self):         raise NotImplementedError("Should have implemented this") 

Because Python doesn't have (and doesn't need) a formal Interface contract, the Java-style distinction between abstraction and interface doesn't exist. If someone goes through the effort to define a formal interface, it will also be an abstract class. The only differences would be in the stated intent in the docstring.

And the difference between abstract and interface is a hairsplitting thing when you have duck typing.

Java uses interfaces because it doesn't have multiple inheritance.

Because Python has multiple inheritance, you may also see something like this

class SomeAbstraction:     pass  # lots of stuff - but missing something  class Mixin1:     def something(self):         pass  # one implementation  class Mixin2:     def something(self):         pass  # another  class Concrete1(SomeAbstraction, Mixin1):     pass  class Concrete2(SomeAbstraction, Mixin2):     pass 

This uses a kind of abstract superclass with mixins to create concrete subclasses that are disjoint.

like image 102
S.Lott Avatar answered Sep 20 '22 17:09

S.Lott