-1

I'm trying to understand the concept of a 'callable'. I've been reading through What is a "callable" in Python? and http://eli.thegreenplace.net/2012/03/23/python-internals-how-callables-work/ .

In simple terms, I think I would sum up a callable as being a method , function or class that has a __call__ method. Assuming this is roughly true what 'things' in python are NOT callable, and why are they not? I'm trying to understand better the big picture of what can be called and what can't.

Community
  • 1
  • 1
user1592380
  • 34,265
  • 92
  • 284
  • 515
  • 1
    No. Why would you think it had anything to do with being instantiated? And surely you've answered your own question: things that don't have a `__call__` method aren't callable. – Daniel Roseman Feb 16 '17 at 15:00
  • This seems like a bit of an odd question. Especial when you add the "and why not" part. For some "things" it just wouldn't make sense to be able to call them. Like integers, or strings, or booleans, or list, or modules, etc. I think it would benefit you to be more specific with what "things" are. – Christian Dean Feb 16 '17 at 15:02
  • `ClassName()` instantiates a class. `function_name()` runs a function. They're both callable because calling them means something. `42()` means nothing. `"hello"()` means nothing. So they're not callable. – khelwood Feb 16 '17 at 15:03
  • To answer your question: everything in Python is callable if it has a `__call__` method. Now if your asking why those things don't have a `__call__` method...well.... – Christian Dean Feb 16 '17 at 15:05
  • Thank you, It is an odd question, and probably badly phrased but I think you have helped me here by mentioning " integers, or strings, or booleans" as things that wouldn't make sense to be called. – user1592380 Feb 16 '17 at 15:09
  • "Things" are called objects in Python. :) – HiFile.app - best file manager Feb 16 '17 at 15:11

1 Answers1

1

Things that are not callable are things for which the result of calling 'callable()' on it is false. So for example:

a = 'a'
print callable(a)
print callable(a.capitalize)
>> False
>> True

So a string is not callable, but the string method capitalize() which returns a copy of the string in all caps, is callable.

l = [1, 2]
print callable(l)
>> False

Likewise lists aren't callable. In fact most objects are not callable.

class Test(object):
    my_member = 'A'

t = Test()
print callable(t)
>> False

print callable(Test)
>> True

But as you can see the constructor for the Test class is callable, which is how we construct instances of the class.

Simon Hibbs
  • 5,941
  • 5
  • 26
  • 32