Last active
December 21, 2020 00:49
-
-
Save mattvh/30a7b7292866b83d5f3b875faeca7fde to your computer and use it in GitHub Desktop.
Example for Medium article "Python Decorators Explained"
This file contains hidden or 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
def decorate(func): | |
print("Do something before func()") | |
func() | |
return func #return the original function, unmodified | |
@decorate | |
def hello(): | |
print("Hello, world!") |
This file contains hidden or 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
import urllib.request, json | |
class XKCDThing(object): | |
def __init__(self): | |
self.subscribers = [] | |
def subscriber(self, func): | |
self.subscribers.append(func) | |
return func | |
def publish(self, title, link): | |
for func in self.subscribers: | |
func(title, link) | |
def run(self): | |
url = "https://xkcd.com/info.0.json" | |
with urllib.request.urlopen(url) as req: | |
data = json.loads(req.read().decode()) | |
title = data['safe_title'] | |
link = data['img'] | |
self.publish(title, link) | |
app = XKCDThing() | |
@app.subscriber | |
def eventHandler1(title, link): | |
print("Event handler 1 called!") | |
print(f"Title: {title}") | |
@app.subscriber | |
def eventHandler2(title, link): | |
print("Event handler 2 called!") | |
print(f"Link: {link}") | |
app.run() |
This file contains hidden or 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
def wrap(func): | |
def wrapper(): | |
print("Say hello? Y/N") | |
if input() == "Y": | |
func() | |
else: | |
print("OK.") | |
return wrapper | |
@wrap | |
def hello(): | |
print("Hello, world!") | |
hello() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment