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

No comments:

Post a Comment