On 17/06/16 16:41, boB Stepp wrote: >> Inheritance is a powerful tool but it carries lots of potential for >> problems too,... > > I looked up LSP last night. I can see how I can easily get burned > even on something seemingly simple. One example, which I imagine is > often used, is of a square class inheriting from a rectangle class. > Squares have same sized sides; rectangles not necessarily so. So any > size changing methods from the rectangle class inherited by the square > class can potentially wreak havoc on squares. Am I getting the > essence of the potential issues I might encounter?
Yes, that's one case. Another good example(in Java) is in the book "Effective Java". It uses the example of a superclass which is a collection and has add() and add_many() methods. Now let's say you want to create a counted collection so you override the add() method to add one to a total each time its called. Then you override add_many() to add the number of items in the params list. The problem is that, unknown to you, the inherited add_many() calls self.add() internally so you wind up double counting on add_many()... You need to know about the internals of the superclass to correctly implement your sub class, which breaks the concept of data hiding... There is no way round this its just one of the inherent(sic) issues with OOP, but a good reason to use delegation rather than inheritance if possible. Inheritance is a powerful tool but comes with sharp claws. (Its even worse in a static language like Java but even in Python there are plenty of opportunities to mess up). -- 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