For working professionals
For fresh graduates
More
13. Print In Python
15. Python for Loop
19. Break in Python
23. Float in Python
25. List in Python
27. Tuples in Python
29. Set in Python
53. Python Modules
57. Python Packages
59. Class in Python
61. Object in Python
73. JSON Python
79. Python Threading
84. Map in Python
85. Filter in Python
86. Eval in Python
96. Sort in Python
101. Datetime Python
103. 2D Array in Python
104. Abs in Python
105. Advantages of Python
107. Append in Python
110. Assert in Python
113. Bool in Python
115. chr in Python
118. Count in python
119. Counter in Python
121. Datetime in Python
122. Extend in Python
123. F-string in Python
125. Format in Python
131. Index in Python
132. Interface in Python
134. Isalpha in Python
136. Iterator in Python
137. Join in Python
140. Literals in Python
141. Matplotlib
144. Modulus in Python
147. OpenCV Python
149. ord in Python
150. Palindrome in Python
151. Pass in Python
156. Python Arrays
158. Python Frameworks
160. Python IDE
164. Python PIP
165. Python Seaborn
166. Python Slicing
168. Queue in Python
169. Replace in Python
173. Stack in Python
174. scikit-learn
175. Selenium with Python
176. Self in Python
177. Sleep in Python
179. Split in Python
184. Strip in Python
185. Subprocess in Python
186. Substring in Python
195. What is Pygame
197. XOR in Python
198. Yield in Python
199. Zip in Python
Python, a powerful language in software development, supports interfaces, a core concept in object-oriented programming. Interfaces provide a blueprint for structuring classes, ensuring they adhere to specific rules and requirements, and fostering maintainable and robust code.
Interfaces are fundamental in Python's object-oriented programming, enabling well-structured, extensible code. This article covers interface declaration, implementation, the role of methods, interface inheritance, and the relationship with abstract classes. Practical examples demonstrate creating and implementing interfaces, showcasing informal and formal interfaces, and with introducing the "zope.interface" library. Additionally, it explores the significance of the Interface Segregation Principle for software design.
In Python, interfaces are created through abstract base classes (ABCs). These are defined in the ABC module, allowing the declaration and enforcement of interfaces. You can declare an interface by creating a subclass of abc.ABC
Example:
In this example, we've defined a Shape interface with two abstract methods: area and perimeter. Any class that wants to be considered a shape must implement these methods. It's Python's behavior to raise a TypeError when an abstract method is not implemented.
Now, let's create a class that implements this interface.
The Circle class inherits from Shape and provides concrete implementations of the area and perimeter methods.
Methods within interfaces serve as a contract for concrete classes to adhere to. These methods define the behavior and functionality expected from any class implementing the interface.
Consider our Shape interface, which has two abstract methods: area and perimeter. Let's look into how these methods work in the context of an interface.
Example: Using Methods in an Interface
In this example, the Shape interface defines two abstract methods: area and perimeter. Any class that implements the Shape interface must provide concrete implementations for these methods. The Circle and Rectangle classes do precisely that.
By using methods in interfaces, you ensure that any class adhering to the interface has a defined structure and behavior, making your code more predictable and maintainable.
Interface inheritance enables the creation of new interfaces by extending existing ones. When one interface inherits from another, it inherits the abstract methods of the parent interface and can introduce new abstract methods.
Consider an example involving two interfaces: Shape and ResizableShape. The Shape interface represents geometric shapes, while the ResizableShape interface inherits from Shape and introduces a method for resizing the shape.
Example: Interface Inheritance
In this example, we have two interfaces, Shape and ResizableShape. The Shape interface defines area and perimeter methods, while the ResizableShape interface inherits from Shape and introduces a new abstract method, resize.
The Circle class implements the ResizableShape interface, which means it must provide concrete implementations for both the area and perimeter methods as well as the new resize method.
Output:
Interface inheritance allows you to build on existing interfaces, promoting code reusability and consistency in your projects.
In Python, an abstract class is a blueprint for other classes and cannot be instantiated. Abstract classes may include abstract methods, which lack a defined implementation. Subclasses of abstract classes must offer concrete implementations for these abstract methods. Python offers the ABC module for defining abstract classes and abstract methods.
Example: Abstract Class and Abstract Methods
In this example, we have an abstract class Shape that defines two abstract methods: area and perimeter. The Circle class is a concrete subclass of Shape and provides concrete implementations for these methods.
Output:
Abstract classes are useful for creating a common structure for related classes and enforcing that subclasses must implement certain methods. This promotes code consistency and provides a clear design pattern.
Interfaces are fundamental in programming, particularly in object-oriented languages like Python, for the following reasons:
Interfaces and abstract classes both define contracts for classes to follow but differ in their implementation and usage. Interfaces are used for enforcing a common structure across unrelated classes, while abstract classes provide a base for related classes with shared functionality.
In Python, interfaces are defined using abstract base classes (ABCs) provided by the ABC module. Abstract base classes serve as a way to declare the methods that must be implemented by classes that inherit from them. Here's an example that demonstrates how to create and implement an interface:
Example: Creating and Implementing an Interface
Output:
Creating and implementing interfaces in Python establishes essential contracts that enhance code consistency and ensure the availability of specific methods across diverse classes.
Creating and implementing interfaces in Python can take different forms, including informal interfaces, formal interfaces, and abstract base classes.
Informal Interface:
An informal interface is not explicitly defined but is rather an agreement between classes based on a shared set of method names.Informal interfaces provide flexibility but rely on conventions and the discipline of developers to adhere to the shared method names.
Formal Interface:
Formal interfaces, also known as abstract classes with abstract methods, are more explicit than informal interfaces. They use abstract base classes (ABCs) from the ABC module to define the interface and ensure that methods are properly implemented.
Abstract Base Class:
An abstract base class (ABC) can serve as both a formal interface and a base class with some concrete methods. It allows for a combination of abstract and concrete methods, and it can be subclassed to provide further specialization.
Registering a virtual subclass with ABCs in Python allows you to specify class adherence to an interface or abstract class without direct inheritance. This is useful when you want to declare a class as a "virtual" subclass of an ABC, even if it doesn't directly inherit from it.
Here's an example:
In this example:
Output:
The Square class is treated as if it's an instance of Shape, and we can call the methods defined in the Shape abstract class on it.
This technique can be useful when you want to declare that a class adheres to a specific interface or abstract class without enforcing a direct inheritance relationship.
Abstract base classes (ABCs) in Python can be used in scenarios involving multiple inheritance to enforce a set of shared methods across different classes. They help create a clear structure for classes that may inherit from multiple sources.
In this example, we'll establish an abstract base class defining a standardized structure for different shapes. We'll subsequently create concrete classes for specific shapes, showcasing multiple inheritance in action.
In this example:
Output:
The Shape abstract base class establishes a consistent structure, with the ColoredShape class providing additional behavior. Rectangle and Circle inherit from these classes to represent specific shapes.
The zope.interface module is a third-party package that provides a way to define and declare interfaces in Python. Let's explore how to declare and use interfaces using zope.interface with an example.
Please note that you need to install the zope.interface package separately. You can typically do this with pip:
Declaring Interfaces with zope.interface
Here's an example of how to declare and use interfaces using the zope.interface module:
In this example:
Using zope.interface facilitates the formal declaration of interfaces, ensuring class adherence to specific contracts with required methods and attributes. Note that while zope.interface is a third-party package. Python's built-in ABC module is commonly used for defining interfaces, depending on project needs.
The Interface Segregation Principle (ISP) emphasizes that classes or modules should not depend on methods they do not use. It advocates creating smaller, focused interfaces tailored to the needs of implementing classes, promoting maintainable and flexible code.
Example
In this example, the Engineer class implements the Worker interface, while the Supervisor class implements both the Worker and Manager interfaces.
By following the Interface Segregation Principle, you create more maintainable and flexible code where classes and interfaces are more cohesive and dependencies are minimized.
In this article, we explored how to define, implement, and use interfaces in Python effectively. Using interfaces in Python allows you to define clear contracts for classes, ensuring that they provide specific methods and attributes. This promotes a more structured and maintainable codebase, making it easier to work collaboratively and adapt to changing requirements.
Q1: What is the difference between an abstract class and an interface in Python?
Q2: When should I use an abstract class, and when should I use an interface?
Q3: How can I create and implement interfaces in Python using third-party packages?
Take our Free Quiz on Python
Answer quick questions and assess your Python knowledge
Author
Talk to our experts. We are available 7 days a week, 9 AM to 12 AM (midnight)
Indian Nationals
1800 210 2020
Foreign Nationals
+918045604032
1.The above statistics depend on various factors and individual results may vary. Past performance is no guarantee of future results.
2.The student assumes full responsibility for all expenses associated with visas, travel, & related costs. upGrad does not provide any a.