Last active
June 30, 2021 06:30
-
-
Save mikeckennedy/7235543fd5964bebabe1e3546ce67d91 to your computer and use it in GitHub Desktop.
Add C# += / -= event subscriptions to Python using the Events package
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Here's the output I get when running locally: