[Tutor] Does composition only work with particular instances of objects?
boB Stepp
robertvstepp at gmail.com
Fri Aug 14 06:31:17 CEST 2015
I was looking at an example illustrating composition from the book,
"Introducing Python" by Bill Lubanovic on p. 140:
>>> class Bill:
def __init__(self, description):
self.description = description
>>> class Tail:
def __init__(self, length):
self.length = length
>>> class Duck:
def __init__(self, bill, tail):
self.bill = bill
self.tail = tail
def about(self):
print('This duck has a', bill.description, 'bill and a',
tail.length, 'tail.')
Here I was mildly surprised that bill and tail were not Bill and Tail,
and in the about method that self.bill was not used in place of
bill.description, etc.
Continuing:
>>> tail = Tail('long')
>>> bill = Bill('wide orange')
>>> duck = Duck(bill, tail)
>>> duck.about()
This duck has a wide orange bill and a long tail.
So I naively thought I could do the following:
>>> bill0 = Bill('narrow rainbow')
>>> tail0 = Tail('ginormous')
And was surprised by:
>>> duck.about()
This duck has a wide orange bill and a long tail.
>>> duck0 = Duck(bill0, tail0)
>>> duck0.about()
This duck has a wide orange bill and a long tail.
>From this I am forced to conclude that composition will only work with
particular instances of objects and not with any old objects created
from their respective classes. Is this understanding correct?
Thanks!
--
boB
More information about the Tutor
mailing list