On Fri, Jan 16, 2009 at 7:51 AM, Vicent <vgi...@gmail.com> wrote: > 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 )
As André showed, this is trivially easy in Python. To expand on his exampl...functions are "first-class objects" in Python. That means that a function is an object that can be used in the same way as other values, i.e. assigned to variables or attributes, passed as function parameters, etc. The introduction of this essay has a bit more about this: http://personalpages.tds.net/~kent37/kk/00001.html > Does it makes any sense? Sure. > 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. All Python values are references, so you are essentially storing a pointer to the function object within the problem. Python assignment does not copy. This is a fundamental concept of Python that often confuses newbies, it is worth taking some time to understand it correctly. My explanation is here: http://personalpages.tds.net/~kent37/kk/00012.html > By the way, I have another related question. In C you can pass arguments to > a function by value or by reference. Is there any equivalence in Python to > that approach? How is the usual way to pass function arguments in Python? This question is the source of endless heat and little light on comp.lang.python, for (IMO) two reasons: - the word 'reference' means two things in this context - 'pass by reference' as a way of parameter passing and 'reference' as a name for a pointer. - the (IMO) correct answer is 'neither'. Python passes object references by value. If you think of it as passing a pointer by value you will pretty much have the right idea. See the second link above for more. Kent _______________________________________________ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor