Showing posts with label abstract. Show all posts
Showing posts with label abstract. Show all posts

Tuesday, March 23, 2010

Python - calling super class methods from derived classes

# An inheritance, abstract classes, and
# calling super class methods from derived

# classes example

class AbstractBot(object):
    def __init__(self):
        self.size = 0
        self.speed = 1
        self.pos = [0,0]
    def applyPos(self, xy):
        self.pos[0] += xy[0] * self.speed
        self.pos[1] += xy[1] * self.speed
    def getCurrentPos(self):
        return self.pos


class WalkingBot(AbstractBot):
    def applyPos(self, xy):
        super(WalkingBot, self).applyPos(xy)
        print "step, step"

class DrivingBot(AbstractBot):
    def applyPos(self, xy):
        super(DrivingBot, self).applyPos(xy)
        print "vroom, vroom"

class RunningBot(AbstractBot):
    def __init__(self):
        super(RunningBot, self).__init__()
        self.speed = 5
    def applyPos(self, xy):
        super(RunningBot, self).applyPos(xy)
        print "trot, trot"

bot1 = WalkingBot()
bot2 = DrivingBot()
bot3 = RunningBot()
bots = [bot1, bot2, bot3]

distance = (1,1)

for step in xrange(3):
    for bot in bots:
        bot.applyPos(distance)
        print 'position: ' + str(bot.getCurrentPos())
        


Monday, March 8, 2010

Python - creating an interface with python

# python doesn't formally support an interface.
# You can work around this and support the spirit

# of an interface by creating abstract classes that
# have empty methods that just raise exceptions if
# haven't been implemented.

class Vehicle:
    def __init__(self, model):
        self.model = model
    def returnModel(self):
        raise NotImplementedError("Subclass must implement")
    def calculateTaxes(self):
        raise NotImplementedError("Subclass must implement")


class Toyota(Vehicle):
    pass


t = Toyota("Carolla")
t.returnModel()

#output:
# NotImplementedError: Subclass must implement

# You are required to implement the defined methods ( just

# like when using an interface