Sobrecarga de operadores em Python

Programação Orientada a Objetos Intermediária em Python

Jake Roach

Data Engineer

Sobrecarga de operadores de comparação

class Person:
  def __init__(self, name):
      self.name = name

  def __eq__(self, other):
      return self.name == other.name

Personalize o funcionamento de ==

  • Use o método mágico __eq__()
  • Recebe self e other
  • Retorna um valor booleano
bryce = Person("Bryce")
orion = Person("Orion")
print(bryce == orion)
False
chuck = Person("Charles Carmichael")
charles = Person("Charles Carmichael")
print(chuck == charles)
True
Programação Orientada a Objetos Intermediária em Python

Somando dois objetos

class Team:
  def __init__(self, team_members):
      self.team_members = team_members

# Create two Team objects, attempt to add them
rookies = Team(["Casey", "Emmitt"])
veterans = Team(["Mike", "Chuck"])
dream_team = rookies + veterans
Traceback (most recent call last):
  File "<stdin>", line 8, in <module>
TypeError: unsupported operand type(s) for +: 'Team' and 'Team'
Programação Orientada a Objetos Intermediária em Python

Sobrecarga do operador +

class Team:
  def __init__(self, team_members):
    # team_members is a list of names
    self.team_members = team_members

  def __add__(self, other):
    # Adding Team objects creates a larger Team
    return Team(self.team_members + other.team_members)
  • Use o método mágico __add__() para sobrecarregar +
  • self e other são passados para __add__()
  • Crie um novo objeto Team usando team_members dos objetos "somados"
Programação Orientada a Objetos Intermediária em Python

Somando dois objetos

# Create two Team objects
rookies = Team(["Casey", "Emmitt"])
veterans = Team(["Mike", "Chuck"])

# Attempt to add these two Teams together
dream_team = rookies + veterans
print(type(dream_team))
print(dream_team.team_members)
Team
["Casey", "Emmitt", "Mike", "Chuck"]
Programação Orientada a Objetos Intermediária em Python

Usando + para criar um novo tipo de objeto

class Team:
  def __init__(self, team_members):
      self.team_members = team_members

class Employee:
  def __init__(self, name, title):
    self.name = name
    self.title = title

  def __add__(self, other):
    # Use the + operator to create a
    # Team with the name of each Employee
    return Team([self.name, other.name])

E se quisermos criar um Team combinando objetos Employee?

  • __add__ é implementado na classe Employee
  • Cria um novo Team gerando uma lista com os nomes dos Employee
  • O resultado de somar dois Employee é um único Team
Programação Orientada a Objetos Intermediária em Python

Some dois objetos para criar um novo objeto

# Create two Employee objects
anna = Employee("Anna", "Technical Specialist")
jeff = Employee("Jeffrey", "Musician")

# Now, attempt to add these together to create a team
audio_team = anna + jeff
print(type(audio_team))
print(audio_team.team_members)
Team
["Anna", "Jeffrey"]
Programação Orientada a Objetos Intermediária em Python

Sobrecarga de outros operadores

Operador Método mágico Tipo de operador
- __sub__ Aritmético
!= __ne__ Comparação
< __lt__ Comparação
> __gt__ Comparação
+= __iadd__ Atribuição
and __and__ Lógico
in __contains__ Pertinência
is __is__ Identidade

 

 

 

 

 

 

 

... E muito mais!

Programação Orientada a Objetos Intermediária em Python

Vamos praticar!

Programação Orientada a Objetos Intermediária em Python

Preparing Video For Download...