Created
June 23, 2020 02:54
-
-
Save wesleyit/121457bf56db199ad60aa87aaa04ef80 to your computer and use it in GitHub Desktop.
This snippet of code demonstrates how to create a class which runs any method you want. Using metaprogramming, a generic method is defined, and this method can call other methods or give a default answer.
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
''' | |
This snippet of code demonstrates how to create a class which | |
runs any method you want. Using metaprogramming, a generic method | |
is defined, and this method can call other methods or give a | |
default answer. | |
''' | |
class StrangeDog: | |
''' | |
I am not going to define a builder method here, as I want to | |
be able to build the class using any parameters. | |
''' | |
def __getattr__(self, name): | |
''' | |
__getattr__ is executed every time I call a parameter that | |
does not exist. This is the generic method. | |
''' | |
def default_method(*args, **kwargs): | |
print('This is a call for: ', name, args, kwargs) | |
return default_method | |
def bark(self): | |
print('Woof! Woof! Woof! Woof!') | |
# Let's create a Strange dog. | |
lulu = StrangeDog() | |
lulu.bark() | |
lulu.bark_to_the_moon(moon='full') | |
lulu.howl('auuuuuuuuuuuuuuuu') | |
lulu.transform_into_werewolf(scary=True, how_much_scary='a lot') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment