top

Search

Python Tutorial

.

UpGrad

Python Tutorial

Interface in Python

Introduction

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.

Overview

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.

Declaring Interface in Python

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:

A screen shot of a computer 
Description automatically generated

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.

Implementing Interface in Python

Now, let's create a class that implements this interface.

A screenshot of a computer Description automatically generated

The Circle class inherits from Shape and provides concrete implementations of the area and perimeter methods. 

Methods in Interfaces

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 in Python

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.

Abstract Classes in Python

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.

Interface: Why are They So Crucial?

Interfaces are fundamental in programming, particularly in object-oriented languages like Python, for the following reasons:

  1. Abstraction and Standardization: Interfaces offer abstraction and standardization, ensuring a common structure and behavior for implementing classes and enhancing code consistency.

  2. Polymorphism: Interfaces simplify interactions between objects of different classes, promoting code modularity and maintainability.

  3. Code Organization: Interfaces separate contracts from implementations, making complex systems more manageable and comprehensible.

  4. Extensibility and Flexibility: Interfaces facilitate code extension and modification, adapting to evolving requirements.

  5. Testing and Debugging: Defined structures in interfaces simplify testing and debugging, focusing on expected behaviors.

  6. Code Reusability: Interfaces encourage code reuse, reducing redundancy and promoting efficient code sharing.

  7. Design by Contract: Interfaces enforce clear specifications, ensuring reliability and consistency.

  8. Collaborative Development: Interfaces establish clear collaboration boundaries, enabling seamless integration in collaborative software development.

Interface vs. Abstract Class 

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.

Creating and Implementing Interfaces in Python

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 Using Abstract Base Classes

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:

  1. We introduce an abstract base class, Shape, featuring abstract methods, area, and perimeter.

  2. A concrete class, Square, is crafted, offering explicit implementations for area and perimeter despite not inheriting directly from Shape.

  3. Square is virtually registered as a subclass of Shape using the register method, enabling it to be treated as if it directly inherits from Shape.

  4. An instance of the Square class is generated, allowing the invocation of area and perimeter methods, resembling an instance of Shape.

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. 

ABCs and Multiple Inheritance

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:

  1. We define an abstract base class, Shape, with abstract methods for area and perimeter, establishing a common structure for various shapes.

  2. A derived class, ColoredShape, is created to represent shapes with color and introduces the display_color method.

  3. The Rectangle and Circle classes utilize multiple inheritance, inheriting from both Shape and ColoredShape. They implement methods for area, perimeter, and display color, unifying shape characteristics and color representation.

  4. Instances of Rectangle and Circle demonstrate the utilization of methods from both inheritance branches, encapsulating both shape properties and color information.

Output:

A screen shot of numbers 
Description automatically generated

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.

Interface Declaration: “ zope.interface”

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:

  1. We import necessary classes and functions from zope.interface.

  2. We define two interfaces, IShape and IColor, using the Interface class, specifying methods and attributes for implementing classes. IColor includes an attribute, color.

  3. The Rectangle class is created, marked as implementing both IShape and IColor using the @implementer decorator. It offers concrete implementations for the methods and attributes defined in these interfaces.

  4. An instance of Rectangle is generated and validated against the interfaces using the verifyObject function, confirming that the object meets the interface requirements.

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.

Interface Segregation Principle

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 

A screen shot of a computer program 
Description automatically generated

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. 

Conclusion

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.

FAQs

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

  • An abstract class can contain both abstract (unimplemented) and concrete (implemented) methods. Subclasses of an abstract class must provide implementations for abstract methods. In contrast, an interface only contains method signatures without implementations, and classes implementing the interface must provide implementations for all methods.

Q2: When should I use an abstract class, and when should I use an interface?

  • Use abstract classes when you want to provide a common base class with some shared functionality, allowing certain methods to be overridden by subclasses. Use interfaces when you want to define a contract that unrelated classes must adhere to, ensuring a common structure and behavior.

Q3: How can I create and implement interfaces in Python using third-party packages?

  • You can use the zope.interface package to create and implement interfaces formally. Define interfaces as classes with abstract methods and use the @implementer decorator to indicate which classes implement those interfaces.

Leave a Reply

Your email address will not be published. Required fields are marked *