हल: पायथन __उप__ जादू विधि

पायथन में __sub__ जादू पद्धति का उपयोग एक फ़ंक्शन को कॉल करने के लिए किया जाता है जो दो तर्क लेता है, लेकिन पहले तर्क को दूसरे तर्क वर्ग के उपवर्ग के रूप में व्याख्या किया जाता है। यह अप्रत्याशित व्यवहार का कारण बन सकता है यदि उपवर्ग __sub__ जादू पद्धति को लागू नहीं करता है।

The __sub__ magic method is used to implement the subtraction operator for objects. It is called when the - operator is used on two objects of the same type. The __sub__ method should return the result of the subtraction operation.

For example, if we have a class that represents a complex number, we could define the __sub__ method like this:

class ComplexNumber: def __init__(self, real, imaginary): self.real = real self.imaginary = imaginary def __sub__(self, other): return ComplexNumber(self.real - other.real, self.imaginary - other.imaginary)

Now we can use the - operator on two ComplexNumber objects:

c1 = ComplexNumber(1, 2) c2 = ComplexNumber(3, 4) c3 = c1 - c2 print(c3) # Prints ComplexNumber(real=-2, imaginary=-2)

जादू विधि क्या है

पायथन में, मैजिक मेथड एक विशेष प्रकार का फ़ंक्शन है जो आपको किसी फ़ंक्शन को उसके नाम को निर्दिष्ट किए बिना कॉल करने की अनुमति देता है। यह कार्य के नाम के आगे एंपरसेंड (&) लगाकर किया जाता है।

मैजिक मेथोड्स की सूची

पायथन में जादू करने के कई अलग-अलग तरीके हैं। यहाँ कुछ है:

1. यादृच्छिक आयात करें
2. आयात समय
3. गणित से आयात sqrt, पाई
4. दिनांक समय आयात दिनांक, समय से
5. ऑपरेटर आयात से जोड़ें, घटाएं, गुणा करें, विभाजित करें
6. functools से आंशिक आयात करें
7. संग्रह आयात डेक से

संबंधित पोस्ट:

एक टिप्पणी छोड़ दो