ramakrishna reddy wrote:
> Can you please explain the functionality of collections.Callable ? If
> possible with a code snippet.
That's a pretty exotic beast that you stumbled upon.
>>> from collections.abc import Callable
You can use it to check if an object is callable, i. e. works like a
function:
>>> isinstance("foo", Callable)
False
>>> isinstance(str, Callable)
True
>>> isinstance(lambda: 42, Callable)
True
You can also use it as a baseclass if you want to prevent subclasses from
being instantiated unless they implement a __call__() method which makes
those instances callable:
>>> class C(Callable): pass
...
>>> c = C()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: Can't instantiate abstract class C with abstract methods __call__
>>> class D(C):
... def __call__(self, name="Al"):
... return "You can call me {}".format(name)
...
>>> d = D()
>>> isinstance(d, Callable)
True
>>> d()
'You can call me Al'
_______________________________________________
Tutor maillist - [email protected]
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor