user628030
user628030

Reputation: 21

Error calling function from dictionary

I just want to create a class with a lot of functions which need to import some variables of the class for there output. To make the use more efficient i wanted to store the functions in a dictionary, but somehow that is not working at all...


class A(object):

    var = 'hello'
    def g(self,x):
        return self.var
    dict = {'g':g}


if __name__ == "__main__":

    a = A()
    print a.g(0)
    print a.dict['g'](0)

OUTPUT

hello
    print a.dict['g'](0)
TypeError: g() takes exactly 2 arguments (1 given)

what is happening within the dictionary with the function g???

Upvotes: 2

Views: 1219

Answers (2)

Steef
Steef

Reputation: 34665

In addition to Jan Hudec's answer, you could also do without dict entirely by using the getattr() built-in function, like so:

class A(object):

    var = 'hello'
    def g(self,x):
        return self.var


if __name__ == '__main__':
    a = A()
    print a.g(0)
    print getattr(a, 'g')(0)

With the advantage of keeping your classes clean.

Upvotes: 0

Jan Hudec
Jan Hudec

Reputation: 76236

When a function is called as a method, it implicitly gets the invocant as first argument. But that's not the case when you pull it out of the dict. You you'd have to call

print a.dict['g'](a, 0)

On a side note, I'd expect the call through dict to be slower, not faster, because you first need to get the dict from the object, which is itself basically equivalent to getting the method.

Upvotes: 4

Related Questions