1

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.

2
  • 2
    Why don't you take advantage of inheritance? It will be also better to include a minimal example of what you're trying to do so we can provide better answers. Commented Mar 27, 2014 at 9:46
  • i have a class named device, and for each new device that i add to my code i have a different methhod that calculates cost, what i want is when i add the divice to add its method and to be able then to call it from tha class. i want each instance to call a differnet method Commented Mar 27, 2014 at 9:54

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

2 Comments

ok thank you very much!!!i'll try it with subclasses. as i said i am a newbie in python and oop and and i still write as if it is C, :)
In that case, instead of focusing on python, it would be worth it to read a bit on the concepts of object oriented design. Probably see them in a different language, in parallel to python, to differentiate the ideas from the ways they are implemented in each language. I would suggest to look into the book "thinking in java" (you can find it online), and read the chapters related to objects, interfaces and polymorphism, which has a very clear introduction to the main concepts. After that, try to read some basic design patterns.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.