class ToDictMixin:
"""A mixin to add a to_dict method to a class."""
def to_dict(self):
return {key: value for key, value in self.__dict__.items() if not key.startswith('__')}
# Use the mixin in two different classes
class User(ToDictMixin):
def __init__(self, username, email):
self.username = username
self.email = email
self.is_active = True
class Product(ToDictMixin):
def __init__(self, name, price):
self.name = name
self.price = price
# Now, both User and Product instances can use the to_dict method
user = User("john_doe", "john.doe@example.com")
print(user.to_dict())
# Output: {'username': 'john_doe', 'email': 'john.doe@example.com', 'is_active': True}
product = Product("Laptop", 1200)
print(product.to_dict())
# Output: {'name': 'Laptop', 'price': 1200}
import logging
# Configure basic logging
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')
class LoggingMixin:
"""A mixin for adding logging capabilities to a class."""
def log_info(self, message):
logging.info(f"{self.__class__.__name__}: {message}")
class DataProcessor(LoggingMixin):
def process_data(self, data):
self.log_info(f"Starting to process data: {data}")
# ... processing logic ...
self.log_info("Finished processing data.")
class Notifier(LoggingMixin):
def send_notification(self, message):
self.log_info(f"Sending notification: '{message}'")
# ... notification logic ...
processor = DataProcessor()
processor.process_data([1, 2, 3])
notifier = Notifier()
notifier.send_notification("System update complete.")