शुरू करेंमुफ़्त में शुरू करें

एक factory method बनाना

अब जब आप factory methods बनाना शुरू करने के लिए तैयार हैं, तो आप factory method design pattern का उपयोग करके एक Checkout क्लास बनाकर शुरुआत करेंगे। नीचे आपके लिए Customer इंटरफेस दिया गया है, साथ ही RewardsMember और NewCustomer concrete products भी। नीचे देखिए!

class Customer(ABC):
  @abstractmethod
  def make_payment(self, price):
    pass

class RewardsMember(Customer):
  def make_payment(self, price):
    print(f"""Total price for rewards member is 
          ${price * .90}, which is 10% off""")

class NewCustomer(Customer):
  def make_payment(self, price):
    print(f"""Total price for new customer is ${price}""")

यह अभ्यास पाठ्यक्रम का हिस्सा है

Intermediate Object-Oriented Programming in Python

पाठ्यक्रम देखें

अभ्यास निर्देश

  • एक _get_customer() factory method बनाएँ, जो customer_type ले और उपयुक्त concrete product का ऑब्जेक्ट रिटर्न करे।
  • complete_transaction() मेथड में, पहले से परिभाषित factory method का उपयोग करके एक customer रिटर्न करें, फिर make_payment() मेथड में पास किए गए price का उपयोग करके भुगतान कराएँ.

इंटरैक्टिव व्यावहारिक अभ्यास

इस अभ्यास को इस नमूना कोड को पूरा करके आज़माएँ।

class Checkout:
  # Create a _get_customer() factory method 
  def ____(self, customer_type):
    if ____ == "Rewards Member":
      return ____()
    elif ____ ____ "New Customer":
      return ____()
  
  # Define the complete_transaction() method
  def complete_transaction(self, customer_type, price):
    customer = ____.____(____)
    ____.____(____)
कोड संपादित करें और चलाएँ