from friend import Friend
def main():
myFriend = Friend("john")
myFriend.name = "mike"
if __name__ == "__main__":
main()
from event import ObjectWithEvents
class Friend(ObjectWithEvents):
def __init__(self, name):
self.__name = name
self.addEvent("changed", self.welcome)
@property
def name(self):
return self.__name
@name.setter
def name(self, value):
if value:
self.__name = value
self.triggerEvent("changed")
def welcome(self):
print("Welcome, to a friend of mine", self.__name.title())
class ObjectWithEvents:
callbacks = None
def addEvent(self, eventname, callback):
if self.callbacks is None:
self.callbacks = {}
if eventname not in self.callbacks:
self.callbacks[eventname] = [callback]
else:
self.callbacks[eventname].append(callback)
def triggerEvent(self, eventname):
if self.callbacks is not None and eventname in self.callbacks:
for callback in self.callbacks[eventname]:
callback()