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

Overloading +

सिर्फ comparison ऑपरेटर्स ही नहीं, बल्कि अन्य ऑपरेटर्स भी ओवरलोड किए जा सकते हैं। Python में क्लासेज़ + और - जैसे arithmetic ऑपरेटर्स के लिए कस्टम फंक्शनैलिटी लागू कर सकती हैं। इस उदाहरण में, आप Storage क्लास के लिए + ऑपरेटर को ओवरलोड करने का अभ्यास करेंगे.

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

Intermediate Object-Oriented Programming in Python

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

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

  • Storage क्लास के लिए + ऑपरेटर को ओवरलोड करने हेतु एक मैजिक मेथड परिभाषित करें.
  • एक नया Storage ऑब्जेक्ट total_storage नाम से बनाएँ, जिसकी capacity दोनों ऑब्जेक्ट्स की संयुक्त capacity के बराबर हो.
  • onboard_storage और external_drive ऑब्जेक्ट्स को जोड़कर total_storage ऑब्जेक्ट बनाएँ, और total_storage की capacity प्रिंट करें.

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

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

class Storage:
  def __init__(self, capacity):
    self.capacity = capacity
  
  def ____(____, ____):  # Overload the + operator
    # Create a Storage object with the sum of capacity
    return ____(self.____ + other.____)

onboard_storage = Storage(128)
external_drive = Storage(64)

# Add the two Storage objects, show the total capacity
total_storage = ____ + ____
print(total_storage.____)
  
कोड संपादित करें और चलाएँ