Computer >> कंप्यूटर ट्यूटोरियल >  >> प्रोग्रामिंग >> Python

Python __lt__ और __gt__ कस्टम (ओवरलोडेड) ऑपरेटर्स कैसे लागू करें?


Python में __lt__ और __gt__ मैजिक मेथड्स को लागू करना

Python में ऑपरेटर्स के ओवरलोडेड व्यवहार को परिभाषित करने के लिए मैजिक मेथड्स हैं। तुलना ऑपरेटर्स (<, <=, >, >=, == और !=) को __lt__, __le__, __gt__, __ge__, __eq__ और __ne__ मैजिक मेथड्स को परिभाषा प्रदान करके ओवरलोड किया जा सकता है। निम्नलिखित प्रोग्राम distance क्लास के ऑब्जेक्ट्स की तुलना करने के लिए < और > ऑपरेटर्स को ओवरलोड करता है।

class distance:
    def __init__(self, x=5, y=5):
        self.ft = x
        self.inch = y
    def __eq__(self, other):
        if self.ft == other.ft and self.inch == other.inch:
            return "both objects are equal"
        else:
            return "both objects are not equal"
    def __lt__(self, other):
        in1 = self.ft * 12 + self.inch
        in2 = other.ft * 12 + other.inch
        if in1 < in2:
            return "first object smaller than other"
        else:
            return "first object not smaller than other"
    def __gt__(self, other):
        in1 = self.ft * 12 + self.inch
        in2 = other.ft * 12 + other.inch
        if in1 > in2:
            return "first object greater than other"
        else:
            return "first object not greater than other"

d1 = distance(5, 5)
d2 = distance()
print(d1 > d2)
d3 = distance()
d4 = distance(6, 10)
print(d1 < d2)
d5 = distance(3, 11)
d6 = distance()
print(d5 < d6)

परिणाम __lt__ और __gt__ मैजिक मेथड्स के कार्यान्वयन को दर्शाता है।

first object not greater than other
first object not smaller than other
first object smaller than other
  1. - पायथन में कस्टम एक्सेप्शन को कस्टम मैसेज के साथ कैसे इम्प्लीमेंट करें?

    दिए गए कोड के लिए समाधान निम्न प्रकार से है: उदाहरण class CustomValueError(ValueError): def __init__(self, arg): self.arg = arg try: a = int(input(Enter a number:)) if not 1 < a < 10: raise CustomValueError(Value must be within 1 and 10.) except CustomValueError as e:

  1. - आधुनिक पायथन में कस्टम एक्सेप्शन कैसे घोषित करें?

    आधुनिक पायथन में कुछ ओवरराइड करने या एक्सेप्शन को अतिरिक्त आर्गुमेंट्स पास करने के लिए हम इसे इस तरह करते हैं: class ValidationError(Exception): def __init__(self, message, errors): super(ValidationError, self).__init__(message) self.errors = errors इस तरह हम एरर मैसेजेस की डिक्श

  1. - पायथन में यूजर डिफाइंड एक्सेप्शन कैसे इम्प्लीमेंट करें?

    हम पायथन में एक नई एक्सेप्शन क्लास बनाकर यूजर-डिफाइंड या कस्टम एक्सेप्शन बनाते हैं। विचार कस्टम एक्सेप्शन क्लास को एक्सेप्शन क्लास से प्राप्त करना है। अधिकांश बिल्ट-इन एक्सेप्शन अपने एक्सेप्शन को लागू करने के लिए उसी विचार का उपयोग करते हैं। दिए गए कोड में, आपने एक यूजर-डिफाइंड एक्सेप्शन क्लास बनाई