English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
Você pode alterar o significado dos operadores no Python com base nos operandos usados. Essa prática é chamada de sobrecarga de operadores.
Operadores do PythonPara classes integradas. Mas o mesmo operador tem comportamentos diferentes para diferentes tipos. Por exemplo,+Os operadores executarão a adição aritmética de dois números, mesclar duas listas e conectar duas strings.
Esta funcionalidade no Python permite que o mesmo operador tenha diferentes significados dependendo do contexto, o que é conhecido como sobrecarga de operadores.
Então, o que acontece quando usamos esses objetos de classes definidas pelo usuário? Vamos ver a classe a seguir, que tenta simular um ponto em um sistema de coordenadas bidimensional.
Exemplo class Point: def __init__(self, x = 0, y = 0): self.x = x
Agora, execute o código e tente adicionar dois pontos no shell do Python.
>>> p1 = Point(2) < Point(3, >>> p2 = Point(-1) < Point(2, >>> p1 + p2 Traceback (última chamada mais recente): ... TypeError: tipo de operando não suportado para +: 'Point' e 'Point'
Uau! Isso é muitos erros. TypeError gerado devido ao Python não saber como somar dois objetos Point.
Mas a boa notícia é que podemos ensinar isso ao Python através da sobrecarga de operadores. Mas antes disso, vamos entender melhor as funções especiais.
As funções especiais que começam com dois sublinhados __ são chamadas de funções especiais no Python. Isso porque, elas não são funções normais. A função __init__() que definimos acima é uma delas. Ela é chamada sempre que criamos um novo objeto da classe. No Python, há muitos funções especiais.
Using special functions, we can make our class compatible with built-in functions.
>>> p1 = Point(2) < Point(3, >>> print(p1, <__main__.Point object at 0x00000000031F8CC0>
The print output did not reach the expected effect. But if we define the __str__() method in the class, we can control its print output. We add this to our class.
Exemplo class Point: def __init__(self, x = 0, y = 0): self.x = x self.y = y def __str__(self):1return "({0},"
Now, let's try the function again with print().
>>> p1 = Point(2) < Point(3, >>> print(p1, (2) < Point(3,
It turns out that it is better when we use the built-in functions str() or format(). They call the same method format().
>>> str(p1, '('2) < Point(3) >>> format(p1, '('2) < Point(3)
Therefore, when you execute str(p1) or format(p1) when Python internally executes p1__str__() is so named, special functions. Let's continue with operator overloading.
to overload+Symbol, we will need to implement the __add__() function in the class. With rights comes great responsibility. We can do anything we like in this function. But it is wise to return a Point object with the sum of coordinates.
Exemplo class Point: def __init__(self, x = 0, y = 0): self.x = x self.y = y def __str__(self):1return "({0}," def __add__(self, other): x = self.x + other.x y = self.y + other.y return Point(x, y)
Now, let's try again.
>>> p1 = Point(2) < Point(3, >>> p2 = Point(-1) < Point(2, >>> print(p1 + p2, (1) < Point(5,
What actually happens is, when you execute p1 + p2when Python calls p1 __add__(p2), which is Point.__add__(p1, p2). Similarly, we can overload other operators. The list of special functions we need to implement is as follows.
operators | expression | Internally |
---|---|---|
Addition (+) | p1 + p2 | p1 __add__(p)2) |
Subtraction (-) | p1-p2 | p1 __sub__(p)2) |
Multiplication (*) | p1 * p2 | p1 __mul__(p)2) |
Power (**) | p1 ** p2 | p1 __pow__(p)2) |
Division (/) | p1 / p2 | p1 __truediv__(p)2) |
Integer division (//) | p1 // p2 | p1 __floordiv__(p)2) |
Modulus (%) | p1%p2 | p1 __mod__(p)2) |
Bitwise left shift (<<) | p1 << p2 | p1 __lshift__(p)2) |
Bitwise right shift (>>) | p1 >> p2 | p1 __rshift__(p)2) |
Operador de e bit a bit (and) | p1 Operador de e bit a bit (and)2 | p1 and p2) |
__ and __ (p | p1 Operador de ou bit a bit (or) 2 | p1 |2) |
__ or __ (p | p1 Operador de exclusão bit a bit (^)2 | p1 ^ p2) |
__ xor __ (pInversão bit a bit | (~)1 | p1 〜p |
Sobrecarga de operadores de comparação em Python
O Python não limita a sobrecarga de operadores a operadores aritméticos. Também podemos sobrecarregar operadores de comparação.
Exemplo class Point: def __init__(self, x = 0, y = 0): self.x = x self.y = y def __str__(self):1return "({0}," })".format(self.x, self.y) def __lt__(self, other): ** 2, + self_mag = (self.x ** 2, (self.y ** 2, + other_mag = (other.x ** 2, (other.y
return self_mag < other_mag
0.1) < Point(1>> Point(-2) < Point(-3, Tente executar esses exemplos no shell do Python. 0.1) < Point(1Verdadeiro5) < Point(-) < Point(0.2, ) 0.1) < Point(1>> Point(1) < Point(1, )
Falso
Sobrecarga de operadores de comparação em Python | Operador | Expressão |
---|---|---|
Menor (<) | p1 <p2 | p1 __ lt __ (p2) |
Menor ou igual (<=) | p1 <= p2 | p1 __ le __ (p2) |
Igual (==) | p1 == p2 | p1 __ eq __ (p2) |
Diferente (!=) | p1!= p2 | p1 __ ne __ (p2) |
Maior (>) | p1> p2 | p1 __ gt __ (p2) |
Maior ou igual (>=) | p1> = p2 | p1 __ ge __ (p2) |