What is the difference between abstract class and interface in Python?
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.
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.
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.
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.
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