Showing posts with label raise. Show all posts
Showing posts with label raise. Show all posts

Monday, July 26, 2010

Python - simple event programming

# simple event programming with python 
# this example is written in p3k ... but can 
# be easily ported to 2.x 
 
# Event Thrower 
class QueenBee(object):
    def __init__(self):
        self.subscriber_to_event_list = []
    def addSubscriberToEvent(self, subscriber, eventText):
        ''' subscribe bees to eventText commands ''' 
        se = (subscriber, eventText)
        self.subscriber_to_event_list.append(se)
    def issueCommand(self, eventText):
        ''' raise event to followers ''' 
        for se in self.subscriber_to_event_list:
            sub = se[0]
            eve = se[1]
            if eve == eventText:
                sub(eve)
 
# event subscriber 
class WorkerBee(object):
    def __init__(self, name, event):
        self.name = name
    def receiveEvent(self, eventName):
        ''' begin work from here ''' 
        print (self.name + " 'By Your Command,' received event: " + eventName)
 
 
 
 
 
qb = QueenBee()
# worker bees 
bList = []
# subscribe bees to commands (events) 
for i in range(10):
    bName = "b"+str(i)
    eventText = "Do More Work" 
    b = WorkerBee(bName, eventText)
    qb.addSubscriberToEvent(b.receiveEvent, eventText)
    bList.append(b)
 
# queen bee issues command that bees are not subscribed to 
print("unscribed to command output: ")
qb.issueCommand("make me a sandwhich")
# nothing happens 
 
print()
print("subscribed event issued:")
# queen bee issues subscribed to event 
qb.issueCommand("Do More Work")
 
 
 
 

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