Thursday, July 7, 2011

Simple python inheritance example

Python's Classes documentation has a bag class. Since I'm writing a program in which I want to do inheritance but haven't done it in a while and need a refresh, I thought I'd extend bag into a wet paper bag; which looses things you put in it nearly half the time. I came up with this:

class Bag(object):
    def __init__(self):
        self.data = []
    def add(self, x):
        self.data.append(x)
    def addtwice(self, x):
        self.add(x)
        self.add(x)

class WetPaper(Bag):
    def __init__(self):
        super(WetPaper, self).__init__()
    def add(self, x):
        from random import randint
        if (randint(1,10) > 4):
            super(WetPaper, self).add(x)

if __name__ == '__main__':
    bag = Bag()
    bag.addtwice(1)
    print "Bag:", bag.data
    wet = WetPaper()
    wet.addtwice(1)
    print "WetPaper:", wet.data
Since I'm extending Bag, defining the constructor was simplified and I didn't have to worry about how add() was implemented; I could just flip a coin with rand to see if the inherited add() should be called. I also didn't have to define addtwice() and it inherited the unreliable aspect of WetPaper's add().

When writing the above, the first thing I had to do was update the original Bag definition to a new style class descended from object. Until I did this I got a "TypeError: must be type, not classobj" error when I used super and I had to directly use the parent class name instead:

    def __init__(self):
        Bag.__init__(self)
While working on this I found Python's Super is nifty, but you can't use it. I also found out that in Python 3 self will become implicit in super calls so instead of:
  super(WetPaper, self).__init__()
I will just be able to do:
  super().__init__()

No comments: