Herança múltipla

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

Jake Roach

Data Engineer

Herança múltipla

Permite que uma classe herde funcionalidades de mais de uma classe

  • Intern pode herdar de Employee e Student
  • Mantém uma relação "é-um"

Uma classe Intern herdando das classes Employee e Student.

class Employee:
  def __init__(self, department):
    self.department = department

  def begin_job(self):
    print(f"Welcome to {self.department}!")
class Student:
  def __init__(self, school):
    self.school = school
    self.courses = []

  def add_course(self, course_name):
    self.courses.append(course_name)
Programação Orientada a Objetos Intermediária em Python

Herança múltipla

class Intern(Employee, Student):
    def __init__(self, department, school, duration):
        # Make a call to BOTH constructors
        Employee.__init__(self, department)
        Student.__init__(self, school)
        self.duration = duration

    def onboard(self, mentor):
        # Implementation of a new method
        ...
Programação Orientada a Objetos Intermediária em Python

Criando um objeto Intern

stephen = Intern("Software Development", "Echo University", 10)
stephen.begin_job()  # Method from Employee
Welcome to Software Development!
stephen.add_course("Intermediate OOP in Python")  # Method from Intern
print(stephen.courses)
["Intermediate OOP in Python"]
Programação Orientada a Objetos Intermediária em Python

Herança em vários níveis

Herdar de uma classe que herda de outra, tornando-se um neto

  • Mantém uma relação "é-um"

Gráfico ilustrando herança em vários níveis.

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

  def introduce(self):
      print(f"Hello, my name is {self.name}")
class Employee(Person):
  def __init__(self, name, title):
    Person.__init__(self, name)
    self.title = title

  def change_position(self, new_title):
    print(f"Starting new role as {new_title}")
    self.title = new_title
Programação Orientada a Objetos Intermediária em Python

Herança em vários níveis

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

    mike = Manager("Mike", "Engineering Manager", 14)
mike.introduce()
mike.change_position("Director of Engineering")
print(mike.number_reports)
Hello, my name is Mike
Starting new role as Director of Engineering
14
Programação Orientada a Objetos Intermediária em Python

Ordem de resolução de métodos (MRO)

A ordem em que o Python decide qual método usar quando pai e filho implementam um método com o mesmo nome

Siga estas regras para determinar a MRO:

  • Primeiro, procura-se nas classes filhas
  • As classes-pai são buscadas da esquerda para a direita, como definidas na declaração da classe

$$

Método .mro() e __mro__

Classe filha herdando múltiplas classes-pai.

1 Beyond the Basic Stuff with Python, Sweigart (p. 311)
Programação Orientada a Objetos Intermediária em Python

Ordem de resolução de métodos (MRO)

class Intern(Employee, Student):  # Intern inherits the Employee and the Student classes
  ...

# Find the MRO for Intern
print(Intern.mro())
[<class '__main__.Intern'>, <class '__main__.Employee'>, <class '__main__.Student'>, <class 'object'>]
# Find the MRO using __mro__
print(Intern.__mro__)
(<class '__main__.Intern'>, <class '__main__.Employee'>, <class '__main__.Student'>, <class 'object'>)
Programação Orientada a Objetos Intermediária em Python

Vamos praticar!

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

Preparing Video For Download...