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.____)