Skip to content

Inheritance V Composition in chapter 8.2.2 #10

@mrbazzan

Description

@mrbazzan

Thanks for this great work.

In chapter 8.2.2 (Substitutability), you gave the following example,

class Slug:
def __init__(self, name):
self.name = name
def crawl(self):
print('slime trail!')
class Snail(Slug): # <1>
def __init__(self, name, shell_size): # <2>
super().__init__(name)
self.name = name
self.shell_size = shell_size
def race(gastropod_one, gastropod_two):
gastropod_one.crawl()
gastropod_two.crawl()
race(Slug('Geoffrey'), Slug('Ramona')) # <3>
race(Snail('Geoffrey'), Snail('Ramona')) # <4>

and further noted the following words:

You could pull more tricks out of your sleeve to make this work,
but consider that this might be a better case for composition.
A snail *has-a* shell, after all. 

Is this code below along the lines of what you were thinking?
Instead of making Snail inherit from Slug, the shell
behavior should be composed into the snail class, and there
shouldn't be any need for inheritance.

class Shell:
    size = None

class Snail:
    def __init__(self, name, shell):
        self.name = name
        self.shell_size = shell.size

Snail("Hafsoh", Shell())

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions