the built-in len is callable and has a __call__ attribute: >>> callable(len) True >>> dir(len) ['__call__', ... ]
1 is not callable and does not have a __call__ attribute: >>> callable(1) False >>> dir(1) [ <a long list that doesn't include __call__>]
As you discovered, trying to call 1 as a function doesn't work: >>> 1() Traceback (most recent call last): File "<stdin>", line 1, in ? TypeError: 'int' object is not callable
A user-defined function is callable and has a __call__ attribute: >>> def f(): pass ... >>> callable(f) True >>> dir(f) ['__call__', ... ] >>>
A class is callable (you call it to create an instance): >>> class C: ... pass ... >>> callable(C) True
Instances of a class, in general, are not callable: >>> c=C() >>> callable(c) False
You can make a class whose instances are callable by defining a __call__ method on the class. This allows you to make a class whose instances behave like functions, which is sometimes handy. (This behaviour is built-in to Python - __call__() is called a special method. There are many special methods that let you customize the behaviour of a class.)
>>> class D: ... def __call__(self, x): ... print 'x =', x ... >>> d=D() # Calling the class creates an instance >>> callable(d) True >>> d(3) # Calling the instance ends up in the __call__() method of the class x = 3
Kent
Dick Moores wrote:
I got this error msg for this line of code:
n = -(2(a**3.0)/27.0 - a*b/3.0 + c) (where a = 1, b = 2, c = 3)
And was baffled until I realized the line should be n = -(2*(a**3.0)/27.0 - a*b/3.0 + c)
But I still don't understand what "callable" means. Can someone help?
Thanks,
Dick Moores [EMAIL PROTECTED]
_______________________________________________ Tutor maillist - [EMAIL PROTECTED] http://mail.python.org/mailman/listinfo/tutor
_______________________________________________ Tutor maillist - [EMAIL PROTECTED] http://mail.python.org/mailman/listinfo/tutor