Created
May 12, 2016 17:44
-
-
Save ihfazhillah/04db06bf357f2fc9d5d38107583dfb92 to your computer and use it in GitHub Desktop.
seperti router web framework, untuk "mungkin" pengganti if else
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
# contoh https://github.com/ihfazhillah/whatsapp-bot-seed/blob/master/src/router.py | |
def cobaA(): | |
print("a") | |
def cobaB(): | |
print("b") | |
routes = [("a", cobaA), | |
("b", cobaB)] | |
class SampleRoute(object): | |
def __init__(self): | |
self.pil = routes # pilihan berupa list of tuple yang berisi pilihan dan callback | |
def route(self, pil): | |
for pilihan, callback in self.pil: | |
match = pilihan == pil # return True kalau sama pilihan user dengan pilihan kondisi | |
if match: | |
callback() # panggil calback | |
break | |
def add_route(self, pilihan, callback): # oh, kita bisa tambah kondisi yang lainnya | |
self.pil.append((pilihan, callback)) | |
if __name__ == "__main__": | |
SampleRoute().route("b") | |
SampleRoute().route("a") | |
SampleRoute().route("c") | |
def jajal(): | |
print() | |
print('ini jajal') | |
print() | |
SampleRoute().add_route("jajal", jajal) | |
SampleRoute().route("jajal") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment