Skip to content

Instantly share code, notes, and snippets.

Embed
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
@property
def age(self):
return self.__age
@age.setter
def age(self, value):
old = self.__age
self.__age = value
if old != value:
self.__events.on_age_changed(self)
@property
def name(self):
return self.__name
@name.setter
def name(self, value):
old = self.__name
self.__name = value
if old != value:
self.__events.on_name_changed(self)
@property
def city(self):
return self.__city
@city.setter
def city(self, value):
old = self.__city
self.__city = value
if old != value:
self.__events.on_location_changed(self)
def main():
p1 = Person("Michael", 47, "Portland")
p2 = Person("Zoe", 50, "Orlando")
p1.on_name_changed += lambda p: print(f"Person changed name to {p.name}.")
p1.on_location_changed += location_changed
p2.on_location_changed += location_changed
# Two moves for Zoe
p2.city = "Seattle"
p2.city = "LA"
# One move for Michael
p1.city = "Vancouver"
# One name change for Michael to Mike
p1.name = "Mike"
# No longer watching for moves for Michael
p1.on_location_changed -= location_changed
p1.city = "Portland"
def location_changed(person: Person):
print(f"Looks like {person.name} has moved to {person.city}")
if __name__ == '__main__':
main()
@mikeckennedy

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
You can’t perform that action at this time.