Last active
June 27, 2019 07:52
-
-
Save psy0rz/ac804b48d3a3133ab84fc622c8c19f1f to your computer and use it in GitHub Desktop.
Call multiple python classes with the same methods and function signatures.
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
class MultiCall(): | |
"""This class calls all methods in multiple other class objects. | |
(all classes should have the same methods and arguments) | |
e.g.: | |
m=MultiCall([A(), B()]) | |
m.msg("hi") | |
will result in a call to A.msg("hi") and B.msg("hi") | |
NOTE: I'll use this in micropython on a ESP32, so low memory usage is essential. | |
Current overhead is 2 extra function calls on the stack and an extra class. | |
""" | |
def __init__(self, classes): | |
for fname in dir(classes[0]): | |
methods=[] | |
for cls in classes: | |
methods.append(getattr(cls, fname)) | |
setattr(self, fname, lambda *args,**kwargs: self.call_all(methods, args, kwargs)) | |
def call_all(self, methods, args, kwargs): | |
for method in methods: | |
method(*args, **kwargs) |
underdarknl
commented
Jun 27, 2019
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment