On Fri, Jan 16, 2009 at 1:51 PM, Vicent <vgi...@gmail.com> wrote: > I am posting this question to two Python forums: Tutor and Python(x,y). > > In the case of Tutor [1], I think it's the right place to ask questions for > a newbie like me. > > In the case of Python(x,y) Discussion Group [2], I am posting also because I > think I am addressing a specific group of Python users that probably > previously dealed with the same problems I do now. Anyway, let me know if > it's a good idea to keep on doing this in the future. > > This question is about how to define classes or objects (or data structures) > I need to use, and how to do it in an efficient way. > > I want to define an object or data structure called "Problem". > > That "problem" has to contain, somehow, a property or element called > "function" which, in fact, I would like it to be a function, or a "pointer" > to a function. > > For example, if "prob" is a "Problem" object, I would like to be able to > do something like this: > > > # call the function in prob, and store the result in "x" : > > x = prob.function( arguments/variables required by the function ) > > > Does it makes any sense? Which would it be the right (meaning efficient but > still object-oriented-programming-compliant) way to do it? > > I mean, if I store "a whole function" within each "Problem" object (assuming > it can be done in Python), each Problem object would be consuming lot of > memory (wouldn't it?). Maybe it would be better just to store a kind of > "pointer" to the function within the "problem" object, so the object would > be "lighter". The function would be then defined outside the object, as > usual. > > Can you give me some hint about this? In fact, this can be done in Python very easily, see the following interactive session:
>>> class test(object): pass >>> test1 = test() >>> test2 = test() >>> def double(x): return x+x >>> def square(x): return x*x >>> test1.f = double >>> test2.f = square >>> test1.f(5) 10 >>> test2.f(5) 25 >>> -- André Engels, andreeng...@gmail.com _______________________________________________ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor