Lahendatud: Python __sub__ maagiline meetod

Pythoni maagilist meetodit __sub__ kasutatakse funktsiooni kutsumiseks, millel on kaks argumenti, kuid esimest argumenti tõlgendatakse teise argumendi klassi alamklassina. See võib viia ootamatu käitumiseni, kui alamklass ei rakenda maagilist meetodit __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)

Mis on maagiline meetod

Pythonis on maagiline meetod funktsiooni eritüüp, mis võimaldab funktsiooni kutsuda ilma selle nime määramata. Selleks lisatakse funktsiooni nime ette ampersand (&).

Maagia meetodite loend

Pythonis on maagia tegemiseks palju erinevaid viise. Siin on mõned:

1. import juhuslikult
2. impordi aeg
3. matemaatika impordist sqrt, pi
4. alates datetime import kuupäev, kellaaeg
5. operaatori impordist liitmine, lahutamine, korrutamine, jagamine
6. functools'ist import osaline
7. kogudest import deque

Seonduvad postitused:

Jäta kommentaar