Real-World Examples of Polymorphism in Python
File I/O Operations
One common example of polymorphism in Python is the use of file I/O operations. The open()
function in Python returns a file object, which provides a common interface for reading, writing, and manipulating files, regardless of the underlying file type or storage medium.
## Example of polymorphism in file I/O operations
with open("example.txt", "r") as file:
content = file.read()
print(content)
with open("example.csv", "w") as file:
file.write("Name,Age,Email\nJohn,30,[email protected]\nJane,25,[email protected]")
In this example, the open()
function returns a file object that can be used to read from or write to a file, regardless of whether it's a text file (.txt
) or a CSV file (.csv
). The file object provides a common set of methods (e.g., read()
, write()
) that can be used to interact with the file, demonstrating polymorphism in action.
Database Interactions
Another example of polymorphism in Python is the use of database interactions. Many Python database libraries, such as SQLAlchemy, provide a common interface for interacting with different database management systems (DBMS), such as MySQL, PostgreSQL, or SQLite.
## Example of polymorphism in database interactions
from sqlalchemy import create_engine, Column, Integer, String
from sqlalchemy.orm import declarative_base
Base = declarative_base()
class User(Base):
__tablename__ = "users"
id = Column(Integer, primary_key=True)
name = Column(String)
email = Column(String)
engine = create_engine("sqlite:///example.db")
Base.metadata.create_all(engine)
session = Session(engine)
user = User(name="John Doe", email="[email protected]")
session.add(user)
session.commit()
users = session.query(User).all()
for user in users:
print(f"{user.name} - {user.email}")
In this example, the SQLAlchemy library provides a common interface for interacting with different database management systems. The create_engine()
function can be used to connect to a variety of DBMS, and the User
class provides a common interface for working with user data, regardless of the underlying database implementation.
Polymorphism is also commonly used in the integration of GUI (Graphical User Interface) toolkits in Python. Libraries like Tkinter, PyQt, and PySide2 provide a set of widgets (e.g., buttons, labels, text boxes) that can be used to build cross-platform GUI applications. These widgets often share a common set of methods and properties, allowing you to write code that works with different types of widgets.
## Example of polymorphism in GUI toolkit integration
import tkinter as tk
from PyQt5.QtWidgets import QApplication, QMainWindow, QPushButton
def show_message(widget):
widget.show_message()
## Tkinter example
class TkinterWindow(tk.Tk):
def show_message(self):
print("Message from Tkinter window")
## PyQt5 example
class PyQtWindow(QMainWindow):
def show_message(self):
print("Message from PyQt5 window")
tkinter_window = TkinterWindow()
pyqt_window = PyQtWindow()
show_message(tkinter_window) ## Output: Message from Tkinter window
show_message(pyqt_window) ## Output: Message from PyQt5 window
In this example, the show_message()
function can work with both Tkinter and PyQt5 window objects, as long as they have a show_message()
method. This demonstrates how polymorphism can be used to write code that is flexible and can work with a variety of GUI toolkit components.
These real-world examples showcase how polymorphism can be leveraged in various domains to create more flexible, maintainable, and extensible Python applications.