Konsep lanjutan Decorators dan Metaclasses dalam Python

 Konsep lanjutan Decorators dan Metaclasses dalam Python, serta memberikan contoh implementasi dalam berbagai industri yang Anda sebutkan.

  1. Decorators

Decorators adalah fungsi yang mengubah perilaku fungsi atau metode lain tanpa mengubah kode sumbernya secara langsung. Mereka biasanya digunakan untuk menambahkan fungsionalitas, logging, mengukur kinerja, atau mengelola akses.

Sintaksis dan Struktur

  • Sebuah dekorator didefinisikan menggunakan sintaks @nama_dekorator sebelum definisi fungsi.
  • Dekorator itu sendiri adalah sebuah fungsi yang menerima fungsi lain sebagai argumen dan mengembalikan fungsi baru yang menambahkan beberapa fungsionalitas.

Keuntungan dan Kasus Penggunaan

Reusability: Dekorator dapat diterapkan pada beberapa fungsi.
Separation of Concerns: Mereka memisahkan kepentingan yang melintang dari logika inti.
Flexibility: Mereka menyediakan cara untuk menambahkan fungsionalitas pada fungsi dan metode secara dinamis.

Contoh sederhana decorator:

python
def log_function_call(func): def wrapper(*args, **kwargs): print(f"Calling function: {func.__name__}") result = func(*args, **kwargs) print(f"Function {func.__name__} completed") return result return wrapper @log_function_call def add(a, b): return a + b result = add(3, 5) print(f"Result: {result}")
  1. Metaclasses

Metaclasses adalah "kelas dari kelas" yang menentukan bagaimana kelas-kelas lain harus dibuat. Mereka dapat digunakan untuk memodifikasi perilaku kelas secara dinamis.

Sintaksis dan Struktur
Metakelas biasanya didefinisikan dengan mewarisi dari tipe dan mengoverride metode seperti __new__ atau __init__.

Keuntungan dan Kasus Penggunaan : 
Custom Behavior: Mereka memungkinkan Anda untuk menyuntikkan perilaku kustom ke dalam pembuatan kelas.
Validation: Anda dapat menerapkan batasan atau memvalidasi atribut kelas.
Class Registration: Mendaftar kelas secara otomatis untuk digunakan di kemudian hari.

Contoh sederhana metaclass:

python
class LoggingMeta(type): def __new__(cls, name, bases, attrs): for attr_name, attr_value in attrs.items(): if callable(attr_value): attrs[attr_name] = cls.log_method(attr_value) return super().__new__(cls, name, bases, attrs) @staticmethod def log_method(method): def wrapper(*args, **kwargs): print(f"Calling method: {method.__name__}") result = method(*args, **kwargs) print(f"Method {method.__name__} completed") return result return wrapper class MyClass(metaclass=LoggingMeta): def method1(self): print("Executing method1") def method2(self): print("Executing method2") obj = MyClass() obj.method1() obj.method2()

Sekarang, mari kita lihat implementasi konsep-konsep ini dalam berbagai industri:

  1. Perbankan dan FinTech:
python
class TransactionLoggingMeta(type): def __new__(cls, name, bases, attrs): for attr_name, attr_value in attrs.items(): if callable(attr_value) and attr_name.startswith('transaction_'): attrs[attr_name] = cls.log_transaction(attr_value) return super().__new__(cls, name, bases, attrs) @staticmethod def log_transaction(method): def wrapper(self, *args, **kwargs): print(f"Starting transaction: {method.__name__}") result = method(self, *args, **kwargs) print(f"Transaction {method.__name__} completed") return result return wrapper class BankAccount(metaclass=TransactionLoggingMeta): def __init__(self, account_number, balance): self.account_number = account_number self.balance = balance def transaction_deposit(self, amount): self.balance += amount return self.balance def transaction_withdraw(self, amount): if self.balance >= amount: self.balance -= amount return self.balance else: raise ValueError("Insufficient funds") account = BankAccount("1234567890", 1000) account.transaction_deposit(500) account.transaction_withdraw(200)
  1. E-commerce:
python
def validate_stock(func): def wrapper(self, product_id, quantity): if self.check_stock(product_id) >= quantity: return func(self, product_id, quantity) else: raise ValueError("Insufficient stock") return wrapper class Ecommerce: def __init__(self): self.inventory = {} def add_product(self, product_id, quantity): self.inventory[product_id] = self.inventory.get(product_id, 0) + quantity def check_stock(self, product_id): return self.inventory.get(product_id, 0) @validate_stock def place_order(self, product_id, quantity): self.inventory[product_id] -= quantity print(f"Order placed for {quantity} units of product {product_id}") ecommerce = Ecommerce() ecommerce.add_product("P001", 10) ecommerce.place_order("P001", 5)
  1. Healthcare:
python
class PrivacyMeta(type): def __new__(cls, name, bases, attrs): for attr_name, attr_value in attrs.items(): if callable(attr_value) and not attr_name.startswith('_'): attrs[attr_name] = cls.ensure_privacy(attr_value) return super().__new__(cls, name, bases, attrs) @staticmethod def ensure_privacy(method): def wrapper(self, *args, **kwargs): if not self.is_authorized(): raise PermissionError("Unauthorized access") return method(self, *args, **kwargs) return wrapper class PatientRecord(metaclass=PrivacyMeta): def __init__(self, patient_id): self.patient_id = patient_id self.authorized = False def is_authorized(self): return self.authorized def authorize(self): self.authorized = True def get_medical_history(self): return f"Medical history for patient {self.patient_id}" def update_treatment(self, treatment): print(f"Updating treatment for patient {self.patient_id}: {treatment}") record = PatientRecord("12345") record.authorize() print(record.get_medical_history()) record.update_treatment("New medication prescribed")
  1. Production and Inventory:
python
def log_inventory_change(func): def wrapper(self, *args, **kwargs): old_quantity = self.get_quantity(args[0]) result = func(self, *args, **kwargs) new_quantity = self.get_quantity(args[0]) print(f"Inventory change: Item {args[0]} - Old: {old_quantity}, New: {new_quantity}") return result return wrapper class InventoryManagement: def __init__(self): self.inventory = {} def get_quantity(self, item_id): return self.inventory.get(item_id, 0) @log_inventory_change def add_item(self, item_id, quantity): self.inventory[item_id] = self.inventory.get(item_id, 0) + quantity @log_inventory_change def remove_item(self, item_id, quantity): if self.inventory.get(item_id, 0) >= quantity: self.inventory[item_id] -= quantity else: raise ValueError("Insufficient inventory") inventory = InventoryManagement() inventory.add_item("A001", 100) inventory.remove_item("A001", 30)
  1. Logistics and Warehouse:
python
class TrackingMeta(type): def __new__(cls, name, bases, attrs): for attr_name, attr_value in attrs.items(): if callable(attr_value) and attr_name.startswith('move_'): attrs[attr_name] = cls.track_movement(attr_value) return super().__new__(cls, name, bases, attrs) @staticmethod def track_movement(method): def wrapper(self, item_id, from_location, to_location): print(f"Tracking: Moving item {item_id} from {from_location} to {to_location}") result = method(self, item_id, from_location, to_location) print(f"Movement completed for item {item_id}") return result return wrapper class WarehouseManagement(metaclass=TrackingMeta): def __init__(self): self.inventory = {} def move_item(self, item_id, from_location, to_location): print(f"Moving item {item_id} from {from_location} to {to_location}") # Actual movement logic here warehouse = WarehouseManagement() warehouse.move_item("B001", "Shelf A", "Shelf B")
  1. Maintenance and Asset Management:
python
def schedule_maintenance(interval_days): def decorator(cls): original_init = cls.__init__ def new_init(self, *args, **kwargs): original_init(self, *args, **kwargs) self.last_maintenance = None self.maintenance_interval = interval_days def check_maintenance(self): if self.last_maintenance is None or (datetime.now() - self.last_maintenance).days >= self.maintenance_interval: print(f"Maintenance required for {self.__class__.__name__}") self.perform_maintenance() else: print(f"No maintenance required for {self.__class__.__name__}") def perform_maintenance(self): print(f"Performing maintenance on {self.__class__.__name__}") self.last_maintenance = datetime.now() cls.__init__ = new_init cls.check_maintenance = check_maintenance cls.perform_maintenance = perform_maintenance return cls return decorator @schedule_maintenance(30) class Machine: def __init__(self, name): self.name = name machine = Machine("Printer") machine.check_maintenance()
  1. Project Management:
python
def log_task_status(func): def wrapper(self, *args, **kwargs): print(f"Starting task: {self.name}") result = func(self, *args, **kwargs) print(f"Task completed: {self.name}") return result return wrapper class Task: def __init__(self, name): self.name = name @log_task_status def execute(self): print(f"Executing task: {self.name}") class Project: def __init__(self, name): self.name = name self.tasks = [] def add_task(self, task): self.tasks.append(task) def run(self): print(f"Starting project: {self.name}") for task in self.tasks: task.execute() print(f"Project completed: {self.name}") project = Project("Website Redesign") project.add_task(Task("Design mockups")) project.add_task(Task("Implement frontend")) project.add_task(Task("Test and deploy")) project.run()
  1. Quality Management:
python
class QualityCheckMeta(type): def __new__(cls, name, bases, attrs): for attr_name, attr_value in attrs.items(): if callable(attr_value) and attr_name.startswith('produce_'): attrs[attr_name] = cls.quality_check(attr_value) return super().__new__(cls, name, bases, attrs) @staticmethod def quality_check(method): def wrapper(self, *args, **kwargs): result = method(self, *args, **kwargs) if self.inspect_quality(result): print("Quality check passed") return result else: print("Quality check failed") return None return wrapper class ProductionLine(metaclass=QualityCheckMeta): def produce_item(self, item_id): print(f"Producing item: {item_id}") return {"item_id": item_id, "quality_score": random.uniform(0, 1)} def inspect_quality(self, item): return item["quality_score"] > 0.7 production = ProductionLine() production.produce_item("C001")
  1. Administrative and Office Automation:
python
def audit_trail(func): def wrapper(*args, **kwargs): print(f"Audit: {func.__name__} called by {getpass.getuser()} at {datetime.now()}") return func(*args, **kwargs) return wrapper class Document: def __init__(self, title, content): self.title = title self.content = content self.created_at = datetime.now() self.modified_at = self.created_at @audit_trail def modify_content(self, new_content): self.content = new_content self.modified_at = datetime.now() class DocumentManagementSystem: def __init__(self): self.documents = {} @audit_trail def add_document(self, document): self.documents[document.title] = document @audit_trail def get_document(self, title): return self.documents.get(title) dms = DocumentManagementSystem() doc = Document("Meeting Minutes", "Discussion points...") dms.add_document(doc) retrieved_doc = dms.get_document("Meeting Minutes") retrieved_doc.modify_content("Updated discussion points...")

Ini adalah beberapa contoh implementasi Decorators dan Metaclasses dalam berbagai industri. Konsep-konsep ini memungkinkan pengembang untuk menambahkan fungsionalitas tambahan, melakukan logging, mengimplementasikan kontrol akses, dan meningkatkan kualitas kode secara keseluruhan.


Comments

Popular posts from this blog

create image slider using phyton in web

Tahukah kamu Algoritma Genetika dan Penerapannya dalam Industri

create animated futuristic profile card using html+css+js

CRUD SPRING REACTIVE WEBFLUX +Mongo DB

Top 7 Digital Transformation Companies

100 perusahaan perangkat lunak (software) populer dari Eropa dan Amerika yang memiliki kehadiran atau operasional di Indonesia.

TOP 8 Framework Populer menggunakan bahasa .NET

Python Date and Time Manipulation

TOP 5 Trends Programming 2024

Daftar Kata Kunci (Keyword) dalam Bahasa Pemrograman Python