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())
Thanks for this great work.
In chapter 8.2.2 (Substitutability), you gave the following example,
practices-of-the-python-pro/ch08/gastropods.py
Lines 1 to 22 in 98bd0a1
and further noted the following words:
Is this code below along the lines of what you were thinking?
Instead of making
Snailinherit fromSlug, the shellbehavior should be composed into the snail class, and there
shouldn't be any need for inheritance.