Interfaces in Python
Interfaces:-
Python does not provide interfaces concept explicitly. It provides abstract classes which can be used as either abstract classes or interfaces. Abstract class can contain both abstract methods and concrete methods where as interface contains only abstract methods. It is not possible to create an object for an interface.
Since an interface contains methods without body, it is not possible to create object to an interface. In this case, we can create subclasses where we can implement all the methods of the interface. Every subclass can provide its own implementation for the abstract methods of the interface.
|
Abstract class |
Interface |
|
It contains both abstract methods and concrete methods |
It contains only abstract methods |
|
You can create object |
You cant create object |
Program
from abc import *
class MyInterface(ABC): #interface having abstract methods only, we can not create object
@abstractmethod
def connect(self):
pass
@abstractmethod
def disconnect(self):
pass
#subclass-Oracle
class Oracle(MyInterface):
def connect(self):
print("I am connecting to Oracle database....")
def disconnect(self):
print("I am disconnecting from the Oracle database...")
#subclass-SYbase
class Sybase(MyInterface):
def connect(self):
print("I am connecting to Sybase Database")
def disconnect(self):
print("I am disconnecting from the sybase database")
str=input("Enter database name")
classname=globals()[str]#globals() is used to convert string into classname
obj=classname()
obj.connect()
obj.disconnect()
Output:-
Enter database nameOracle I am connecting to Oracle database.... I am disconnecting from the Oracle database...
Comments
Post a Comment