Metoda magic __sub__ di Python dipaké pikeun nelepon hiji fungsi nu nyokot dua argumen, tapi argumen kahiji diinterpretasi salaku subclass sahiji kelas argumen kadua. Ieu bisa ngakibatkeun kabiasaan teu kaduga lamun subclass teu nerapkeun __sub__ metoda magic.
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)
Daptar eusi
Naon Métode Magic
Dina Python, métode magic mangrupakeun tipe husus tina fungsi nu ngidinan Anjeun pikeun nelepon hiji fungsi tanpa nangtukeun ngaranna. Hal ieu dilakukeun ku prefixing ngaran fungsi kalawan ampersand (&).
Daptar métode Magic
Aya seueur cara pikeun ngalakukeun sihir dina Python. Ieu sababaraha:
1. impor acak
2. waktos impor
3. ti math impor sqrt, pi
4. ti datetime tanggal impor, waktos
5. ti operator impor nambahkeun, ngurangan, kalikeun, ngabagi
6. ti functools impor parsial
7. ti kumpulan impor deque