Reputation: 91
What i have is for each instance of a class a different method.So what i want is when i make a new intance of that class to be somehow able to choose which method this instance will call.I am a complete newbie in python and i wonder if i could have a list of methods and each instance to call a specific one from this list.Is that even possible?
I did some search and found the http://docs.python.org/2/library/inspect.html (inspect module) but i got confused.
Upvotes: 1
Views: 91
Reputation: 29099
In python, functions are first class objects. So, you can directly pass a function as argument. If you have defined functions f(x), g(x), h(x), you can create a class method
def set_function(self, external_function):
self.F = external_function
You can then use object.F(x), as if it had been defined inside the class.
However, object belonging to the same class having different methods is bad design. If objects of the same class have different behavior, they should probably belong to different classes to begin with. A better approach would be to subclass the original class, define the different functions inside the subclasses, and then instantiate the corresponding objects.
Upvotes: 2