On 14/08/15 05:31, boB Stepp 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.

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.

This is a rubbish example, or at the kindest an incomplete one.
The problem here is that the class about() method is relying on the existence of global variables called bill and tail. In any sane example it should be using the attributes self.bill and self.tail.

If they really did want all instances to share the same bill and tail they should have made them class variables rather than instance ones and used those in about().

So, in normal use of composition you, Bob, would be right and they should use self.bill and self.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.

This is because of the hard coded references to the global
vars bill and tail. If they used self.bill and self.tail
everything would work as you expected.

So, unless the book explains why this is bad practice and
goes on to show a good example, I must conclude its a very
bad example.

--
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos


_______________________________________________
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor

Reply via email to