ઉકેલાયેલ: Python __sub__ જાદુ પદ્ધતિ

પાયથોનમાં __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, pi
4. તારીખથી આયાત તારીખ, સમય
5. ઓપરેટર આયાતમાંથી ઉમેરો, બાદબાકી, ગુણાકાર, ભાગાકાર
6. ફંકટૂલ્સમાંથી આંશિક આયાત કરો
7. સંગ્રહ આયાત ડેકમાંથી

સંબંધિત પોસ્ટ્સ:

પ્રતિક્રિયા આપો