Python डिज़ाइन पैटर्न

Adapter Pattern in Python

Adapter Pattern in Python को संपादित और ऑनलाइन चलाए जा सकने वाले व्यावहारिक उदाहरण से सीखें।

Adapter Pattern क्या है?

Adapter Pattern in Python को संपादित और ऑनलाइन चलाए जा सकने वाले व्यावहारिक उदाहरण से सीखें।

इसका उपयोग कब करें?

  • सिद्ध संरचनाओं से बार-बार आने वाली object-design समस्याएँ हल करें।
  • जिम्मेदारियों को अलग करें ताकि code को बढ़ाना और test करना आसान हो।
  • टीम में architecture पर चर्चा करते समय साझा design शब्दावली का उपयोग करें।

उदाहरण कोड

कोड चलाएँ →
main.py
class LegacyGateway:
    # Adapter: wrap an incompatible API with the expected interface.
    def make_payment(self, cents):
        return f"PAY {cents / 100:.2f}"


class PaymentAdapter:
    def __init__(self, gateway):
        self.gateway = gateway

    def pay(self, dollars):
        # Translate both the method name and amount format.
        return self.gateway.make_payment(round(dollars * 100))


gateway = PaymentAdapter(LegacyGateway())
print(gateway.pay(25))

अपेक्षित आउटपुट

PAY 25.00

यह कैसे काम करता है

यह उदाहरण Adapter Pattern in Python दिखाता है। कोड समझने के लिए इनपुट मान बदलें।

मान बदलें और Python इंस्टॉल किए बिना CodeUtility ऑनलाइन Python कंपाइलर में प्रोग्राम चलाएँ।

अभ्यास के कार्य

बड़े dataset पर जाने से पहले input बदलें और edge cases की जाँच करें।

  1. Pattern की संरचना बनाए रखते हुए उदाहरण का domain बदलें।
  2. Pattern की तुलना सरल implementation से करें और उनके trade-off समझाएँ।
  3. नई implementation जोड़ने से पहले प्रत्येक participant के लिए test लिखें।
Python IDE में चलाएँ →