Module (88%)
Section (71%)

Which way should you choose?

Before we answer the question, let's mention a few more things:

  • inheritance and composition are not mutually exclusive. Real-life problems are hardly every pure “is a” or “has a” cases;
  • treat both inheritance and composition as supplementary means for solving problems;
  • there is nothing wrong with composing objects of ... classes that were built using inheritance. The next example code should shed some light on this case.

You should always examine the problem your code is about to solve before you start coding. If the problem can be modeled using an “is a” relation, then the inheritance approach should be implemented.

Otherwise, if the problem can be modeled using a “has a” relation, then the choice is clear – composition is the solution.

Don't hesitate to experiment and re-implement your solution.


Code

class Base_Computer:
def __init__(self, serial_number):
self.serial_number = serial_number


class Personal_Computer(Base_Computer):
def __init__(self, sn, connection):
super().__init__(sn)
self.connection = connection
print('The computer costs $1000')


class Connection:
def __init__(self, speed):
self.speed = speed

def download(self):
print('Downloading at {}'.format(self.speed))


class DialUp(Connection):
def __init__(self):
super().__init__('9600bit/s')

def download(self):
print('Dialling the access number ... '.ljust(40), end='')
super().download()


class ADSL(Connection):
def __init__(self):
super().__init__('2Mbit/s')

def download(self):
print('Waking up modem ... '.ljust(40), end='')
super().download()


class Ethernet(Connection):
def __init__(self):
super().__init__('10Mbit/s')

def download(self):
print('Constantly connected... '.ljust(40), end='')
super().download()

# I started my IT adventure with an old-school dial up connection
my_computer = Personal_Computer('1995', DialUp())
my_computer.connection.download()

# then it came year 1999 with ADSL
my_computer.connection = ADSL()
my_computer.connection.download()

# finally I upgraded to Ethernet
my_computer.connection = Ethernet()
my_computer.connection.download()
{{ dockerServerErrorMsg }} ×
{{ errorMsg }} ×
{{ successMsg }} ×