Ixazululiwe: Indlela yomlingo yePython __sub__

Indlela yomlingo ethi __sub__ ku-Python isetshenziselwa ukubiza umsebenzi othatha izimpikiswano ezimbili, kodwa impikiswano yokuqala ihunyushwa njengesigaba esingaphansi sesigaba se-agumenti yesibili. Lokhu kungaholela ekuziphatheni okungalindelekile uma i-subclass ingasebenzisi __sub__ indlela yomlingo.

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)

Iyini iMagic Method

Ku-Python, indlela yomlingo iwuhlobo olukhethekile lomsebenzi okuvumela ukuthi ushayele umsebenzi ngaphandle kokucacisa igama lawo. Lokhu kwenziwa ngokufaka kuqala igama lomsebenzi nge-ampersand (&).

Uhlu lwezindlela zomlingo

Kunezindlela eziningi ezahlukahlukene zokwenza umlingo ePython. Nazi ezimbalwa:

1. ukungenisa okungahleliwe
2. isikhathi sokungenisa
3. kusuka ku-sqrt yokungenisa izibalo, pi
4. kusukela ngosuku lokungenisa lwesikhathi sosuku, isikhathi
5. kokungeniswa ko-opharetha engeza, khipha, phindaphinda, hlukanisa
6. kusuka ku-functools ukungenisa ngokwengxenye
7. kusuka kumaqoqo ngenisa i-deque

Okuthunyelwe okuhlobene:

Shiya amazwana