Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /* Test whether an object can be called */
- int
- PyCallable_Check(PyObject *x)
- {
- if (x == NULL)
- return 0;
- if (PyInstance_Check(x)) {
- PyObject *call = PyObject_GetAttrString(x, "__call__");
- if (call == NULL) {
- PyErr_Clear();
- return 0;
- }
- /* Could test recursively but don't, for fear of endless
- recursion if some joker sets self.__call__ = self */
- Py_DECREF(call);
- return 1;
- }
- else {
- return x->ob_type->tp_call != NULL;
- }
- }
- class Cached:
- def __init__(self, function):
- self.function = function
- self.cache = {}
- def __call__(self, *args):
- try: return self.cache[args]
- except KeyError:
- ret = self.cache[args] = self.function(*args)
- return ret
- @Cached
- def ack(x, y):
- return ack(x-1, ack(x, y-1)) if x*y else (x + y + 1)
- class Quitter(object):
- def __init__(self, name):
- self.name = name
- def __repr__(self):
- return 'Use %s() or %s to exit' % (self.name, eof)
- def __call__(self, code=None):
- # Shells like IDLE catch the SystemExit, but listen when their
- # stdin wrapper is closed.
- try:
- sys.stdin.close()
- except:
- pass
- raise SystemExit(code)
- __builtin__.quit = Quitter('quit')
- __builtin__.exit = Quitter('exit')
- class Foo:
- def __call__(self):
- print 'called'
- foo_instance = Foo()
- foo_instance() #this is calling the __call__ method
- >>> type(int).__call__(int)
- 0
- >>> type(object).__call__(object)
- <object object at 0x523460>
- class a(object):
- def __call__(self, *args):
- print 'Hello'
- func = a()
- # or ...
- def func(*args):
- print 'Hello'
- class Adder(object):
- def __init__(self, val):
- self.val = val
- def __call__(self, val):
- return self.val + val
- func = Adder(5)
- print func(3)
- [nigel@k9 ~]$ python
- Python 2.5 (r25:51908, Nov 6 2007, 15:55:44)
- [GCC 4.1.2 20070925 (Red Hat 4.1.2-27)] on linux2
- Type "help", "copyright", "credits" or "license" for more information.
- >>> 'aaa'() # <== Here we attempt to call a string.
- Traceback (most recent call last):
- File "<stdin>", line 1, in <module>
- TypeError: 'str' object is not callable
- >>>
- >>> class Foo:
- ... pass
- ...
- >>> class Bar(object):
- ... pass
- ...
- >>> type(Foo).__call__(Foo)
- <__main__.Foo instance at 0x711440>
- >>> type(Bar).__call__(Bar)
- <__main__.Bar object at 0x712110>
- >>> def foo(bar):
- ... return bar
- ...
- >>> type(foo).__call__(foo, 42)
- 42
- >>> class Foo(object):
- ... def __call__(self):
- ... return 42
- ...
- >>> f = Foo()
- >>> f()
- 42
Add Comment
Please, Sign In to add comment