Skip to content

Latest commit

 

History

History
155 lines (98 loc) · 3.08 KB

multi_inheritance_mixins.md

File metadata and controls

155 lines (98 loc) · 3.08 KB

Lesson: Multiple Inheritance & Mix-ins

📝  Class Materials:

Coding Exercise 1

# Superclass - Parent
class Person:

  def __init__(self, name, age):
    self._name = name
    self._age = age

  def introduce_self(self):
    print(f"My name is {self._name} and my age is {self._age}.")


# create a Person and have them introduce themselves
person_example = Person("Adriana", "28")
person_example.introduce_self()
# create Student class
class Student(Person):

  def __init__(self, name, age, year):
    super().__init__(name,age)
    self._year = year
    self.courses = [] 

  def get_courses(self):
    print(f"{self._name} is taking CS 1.1") 

  def introduce_self(self):
    print(f"My name is {self._name} and I'm a Student")


# create a Student and have them introduce themselves

student_example = Student("Danika", "28", "2022")
student_example.introduce_self()
student_example.get_courses()

#print(help(Student))

Coding Exercise 2

class Mammal:
    pass

class WingedAnimal:
    pass

class Bat(Mammal, WingedAnimal):
    pass



battie = Bat()
print(isinstance(battie, Bat))
print(isinstance(battie, Mammal))
print(isinstance(battie, WingedAnimal))


# TODO: Use issubclass to check if Bat is a subclass of Mammal and WingedAnimal

# Syntax: issubclass(subclass, superclass)

Coding Exercise 3

# main.py

from Bat import Bat

battie = Bat(True)
battie.display()
print(Bat.mro())
print(help(Bat))

# TODO: create initializers in all classes

# TODO: Add a display() method to WingedAnimal, and Mammal. Which display will be called first?


# TODO: Add a display() method to Bat. Which method will be invoked this time when we use .display()?


# TODO: Update the display() method in Bat to call the display methods in Mammal and WingedAnimal


# TODO: Create an init method in WingedAnimal and Mammal. Which init method will be used when we create a Bat object?

# TODO: How can we fix this?
# Bat.py

from Mammal import Mammal
from WingedAnimal import WingedAnimal

class Bat(WingedAnimal, Mammal):
  
  def __init__(self, is_vampire):
    self.is_vampire = is_vampire
    Mammal.__init__(self, False)
    WingedAnimal.__init__(self, True)
# Mammal.py

class Mammal:

  produce_milk = True

  def __init__(self, lays_eggs):
    self.lays_eggs = lays_eggs

  def display(self):
    if self.lays_eggs:
      print("I'm a mammal that can lay eggs")
    else:
      print("I'm a mammal")
# WingedAnimal.py

class WingedAnimal:

  def __init__(self, can_fly):
    self.can_fly = can_fly

  def display(self):
    if self.can_fly:
      print("I'm a winged animal and can fly")
    else:
      print("I'm a winged animal")