On Thu, Aug 13, 2015 at 11:31 PM, boB Stepp <robertvst...@gmail.com> wrote: > 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.
Something went wrong here, either with the example itself or your copying of it. Your instinct is correct, it should be 'self.bill.description' rather than 'bill.description': the Duck.about method as written above will only work in situations where 'bill' and 'tail' happen to be defined in the calling scope. The about method should be: def about(self): print('This duck has a', self.bill.description, 'bill and a', self.tail.length, 'tail.') > 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. Before you fix the about method as I suggested above, try this again but do `del bill, tail` before you call `duck.about()`; the failure may be somewhat enlightening. > 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? Very much not :). You were correct to think this was meant to give you 'This duck has a narrow rainbow bill and a ginormous tail.', but the about method had a serious bug. -- Zach _______________________________________________ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor