Solucionat: mètode màgic Python __sub__

El mètode màgic __sub__ a Python s'utilitza per cridar una funció que pren dos arguments, però el primer argument s'interpreta com una subclasse de la classe del segon argument. Això pot provocar un comportament inesperat si la subclasse no implementa el mètode màgic __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)

Què és el Mètode Màgic

A Python, el mètode màgic és un tipus especial de funció que us permet cridar una funció sense especificar-ne el nom. Això es fa prefixant el nom de la funció amb un ampersand (&).

Llista de mètodes de màgia

Hi ha moltes maneres diferents de fer màgia a Python. Aquí en teniu uns quants:

1. importació aleatòria
2. temps d'importació
3. de matemàtiques importació sqrt, pi
4. des de datetime data d'importació, hora
5. de l'operador importació sumar, restar, multiplicar, dividir
6. des de functools importació parcial
7. de col·leccions importar deque

Articles Relacionats:

Deixa el teu comentari