Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

Probably if you have a trivial piece of code, you don't need inheritance to help you structure it. But you're right that we need a smaller example than the entire class hierarchy of Pygmusic. What do you think would be the smallest sensible example?

If your objective is only to explain what inheritance is rather than why someone would use it, you could probably write two classes and three methods:

    class A:
        def z(self):
            print "z " + self.y()
        def y(self):
            return "Ay"

    class B(A):
        def y(self):
            return "By"

    A().x()
    B().x()
But I really think that most people will find a program easier to understand if it's not completely abstract like that — if it reflects some kind of intentional process where a programmer was trying to achieve something. But in order to explain inheritance in such a context, you need a program where inheritance makes things better instead of worse. What do you think is the simplest possible piece of code that would do that? I am thinking of a very-much-cut-down version of Pygmusic with only two drawable objects.


Device drivers. You have a base class, device, which supports at the minimum, read() and write(). Then you subclass to block and character devices, and so from there. It's a real world example (Unix does it, although in C) and it's simple enough to explain the concepts.


But delegation is a better solution than inheritance for this, i.e. the printer driver class takes a character device instance as a parameter. Delegate the character device's read and write methods to the printer driver's class, make the printer driver do the same interfaces, and done. Now you have something that composes better than inheritance and substitutes anywhere you needed a character device.


irc bots. Or chat bots in general since kids are not familiar with irc nowadays.

It's an amazingly useful teaching tool, since it's real enough to understand it and fake enough that you don't care about taking the bits apart and replacing them. Also, it has a lot of points where you can go and improve the design (extract interfaces, get away with inheritance and use delegation, then get away with objects, then end up with a lisp interpreter etc etc).




Consider applying for YC's Summer 2026 batch! Applications are open till May 4

Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: