AlgoViz

Multiple inheritance

hard 50 min

A class with several parent classes gets the types, the methods and the fields of all of them.

Watch lesson4:37

Out of inheritance

When a side can end.

The point: a parent is for life. People graduate, change jobs and have two jobs. That is a list of roles.

A person with roles

Person- name- roles: Map+ takeRole(kind, role)+ leaveRole(kind)+ role(kind)

1/4One class of people

No Student and no Employee under Person. A human stays one object for life.

has (lives on)implements

Python
class Person:    def __init__(self, name):        self.name = name        self._roles = {}    def take_role(self, kind, role):        self._roles[kind] = role    def leave_role(self, kind):        return self._roles.pop(kind, None)    def role(self, kind):        return self._roles.get(kind)class StudentRole:    def __init__(self, school):        self.school = schoolclass EmployeeRole:    def __init__(self, company):        self.company = companynoor = Person("Noor")noor.take_role(StudentRole, StudentRole("Harbour College"))noor.take_role(EmployeeRole, EmployeeRole("Blue Cafe"))noor.leave_role(StudentRole)                      # graduated, same personprint(noor.role(StudentRole), noor.role(EmployeeRole).company)   # None Blue Cafe
The same Noor before and after graduation.
Edit and run it in your browser

Classes against roles

SidesJoin classes, at mostRole classes
212
343
4114
5265
Join classes are combinations of at least two sides: 2 to the power n, minus n, minus 1.

Moving a live system

  1. 1

    Add roles beside classes

    Person gets role(kind). WorkingStudent answers with itself.

  2. 2

    Move callers

    From isinstance(p, Student) to p.role(StudentRole).

  3. 3

    Move data

    One row per role in the store, with start and end date.

  4. 4

    Make persons

    The factory returns Person with roles. The join classes are used by nobody.

  5. 5

    Delete

    Join classes first, then Student and Employee.

A side with a life of its own

With classes every arrow would be a new object and a copied id.