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???
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.
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.
精彩评论