__call__ question

Rick Richardson r.l.richardson at verizon.net
Tue Oct 1 11:53:20 EDT 2002


 >>> def callfunc(self, arg):
    print "hello, " + arg
 >>> class testclass(object):
    def testfunc():
        print "testing"
 >>> blah = testclass()
 >>> blah
<__main__.testclass object at 0x009336E8>
 >>> blah()
Traceback (most recent call last):
  File "<pyshell#9>", line 1, in ?
    blah()
TypeError: 'testclass' object is not callable
 >>> blah.__call__ = callfunc
 >>> blah("test")
Traceback (most recent call last):
  File "<pyshell#11>", line 1, in ?
    blah("test")
TypeError: 'testclass' object is not callable
 >>> blah.__call__(blah, "test")
hello, test
 >>> testclass.__call__ = callfunc
 >>> blah("test")
hello, test
 >>>

Your example gave me another variant that I should have tried but didn't 
expect to work,
that is adding the function to the Class, not the instance :). It is 
interesting to note that the actual  function call works for either the 
instance or the class, but the shortcut only works for the object if the 
assignment was made to the class.

Michael Hudson wrote:

>Works the same with new-style classes too.  What goes wrong for you?
>
>Cheers,
>M.
>
>  
>







More information about the Python-list mailing list