1

My question is how to program in Python (2.6) a function that uses a namespace of an object, while the function is defined outside the object/class. In addition, that function should only change the variables in the object's namespace; it should not take over the namespace (because with multiple objects they will all use the same namespace).

My reason for pursuing this, is because I wish to write a very small class, where during construction all necessary functions for future use are already given and subsequent function calls (self.__call__) on the object itself can be directly applied.

I realize that this idea is not very pythonic (as they say), and I have thought of various other solutions (such as putting the functions in another class and connecting them), but I can't help but feel that each of these solutions is a lot more work than I would think makes sense.

One simple way that accomplishes what I want is the following:

class A:
    def __init__(self, some_dict, func_a):
        self.memory = some_dict
        self.__call__ = func_a

def test_func(obj, some_input):
    if some_input in obj.memory :
        return obj.memory[some_input]
    else :
        obj.memory[some_input] = 0. # some default value
        return 0.

first_object = A({}, test_func)
print first_object(first_object, '3')

This will work fine, but what aches me is that when I make function calls to the object, I will also have to give the object itself (see the last line). I hope to be able make calls as such:

print first_object('3')

So far, my ideas were unsuccesful to avoid this (e.g. copying the function method and link its namespace by self.__call__.memory = self.memory). I wish to find something to change the def __init__ part to 'adopt' a function and link their namespaces.

I have rigorously searched for an answer on the internet, but a definite solution has not yet been found. The following http://www.velocityreviews.com/forums/t738476-inserting-class-namespace-into-method-scope.html seeks the same, but is also not succesfull.

Anyone have a solution to tackle this?

4

0 回答 0