Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Add C# += / -= event subscriptions to Python using the Events package
from events import Events # Note you must pip install events
class Person:
def __init__(self, name: str, age: int, city: str):
self.__events = Events(('on_name_changed', 'on_age_changed', 'on_location_changed'))
self.on_name_changed = self.__events.on_name_changed
self.on_age_changed = self.__events.on_age_changed
self.on_location_changed = self.__events.on_location_changed
self.__name = name
self.__age = age
self.__city = city
def age(self):
return self.__age
def age(self, value):
old = self.__age
self.__age = value
if old != value:
def name(self):
return self.__name
def name(self, value):
old = self.__name
self.__name = value
if old != value:
def city(self):
return self.__city
def city(self, value):
old = self.__city
self.__city = value
if old != value:
def main():
p1 = Person("Michael", 47, "Portland")
p2 = Person("Zoe", 50, "Orlando")
p1.on_name_changed += lambda p: print(f"Person changed name to {}.")
p1.on_location_changed += location_changed
p2.on_location_changed += location_changed
# Two moves for Zoe = "Seattle" = "LA"
# One move for Michael = "Vancouver"
# One name change for Michael to Mike = "Mike"
# No longer watching for moves for Michael
p1.on_location_changed -= location_changed = "Portland"
def location_changed(person: Person):
print(f"Looks like {} has moved to {}")
if __name__ == '__main__':

This comment has been minimized.

Copy link
Owner Author

@mikeckennedy mikeckennedy commented Aug 5, 2020

Here's the output I get when running locally:

Looks like Zoe has moved to Seattle
Looks like Zoe has moved to LA
Looks like Michael has moved to Vancouver
Person changed name to Mike.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment