Rešeno: čarobna metoda Python __sub__

Čarobna metoda __sub__ v Pythonu se uporablja za klic funkcije, ki sprejme dva argumenta, vendar se prvi argument razlaga kot podrazred razreda drugega argumenta. To lahko povzroči nepričakovano vedenje, če podrazred ne izvaja čarobne metode __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)

Kaj je čarobna metoda

V Pythonu je čarobna metoda posebna vrsta funkcije, ki vam omogoča, da pokličete funkcijo, ne da bi podali njeno ime. To storite tako, da pred ime funkcije dodate znak & (&).

Seznam čarobnih metod

V Pythonu obstaja veliko različnih načinov za čarovništvo. Tukaj je nekaj:

1. uvoz naključno
2. čas uvoza
3. iz matematike uvozi sqrt, pi
4. from datetime datum uvoza, čas
5. iz operatorja uvoz seštej, odštej, pomnoži, deli
6. iz functools import partial
7. iz zbirk uvoz deque

Podobni objav:

Pustite komentar