The title might not be the best description of what I'm trying to do but I'm not sure what to call this. I came across various seemingly related concepts with names like "decorators", "descriptors", and "metaclasses" but I don't know which of those approaches (if any) I should investigate further!
Given the following classes:
def __init__(self, greeting):
self.greeting = greeting
def greet(self, animal):
print(self.greeting + ", " + animal + "!")
animals = ['dog', 'parrot']
I'd like to be able to use an instance of
MyGreeter like this:
greeter = MyGreeter("What's up")
# "What's up, parrot!"
Effectively, I would like it to function as if I had defined
MyGreeter like this instead:
In other words, I want to dynamically define methods (
dog(), etc.) with names derived from an attribute (
animals) of the class (
What is the best way to do this? Thanks a lot!