syntax for making objects callable in python

  • Last Update :
  • Techknowledgy :

In Python, classes, methods, and instances are callable because calling a class returns a new instance. Instances are callable if their class includes __call__() method. ,The callable() method returns True if the object passed is callable, False if not. ,In the above example, the std instance is not callable. Calling the object will raise an error. To make the instance callable, you must override the __call__() method in the student class, as shown below.,The following example checks built-in objects and methods to see if they are callable or not.

Syntax:

callable(object)
2._
print("Is str callable? ", callable(str)) # str class
print("Is len callable? ", callable(len)) # len
function
print("Is list callable? ", callable(list)) # list class

num = 10
print("Is variable callable? ", callable(num))
3._
Is str callable ? True
Is len callable ? True
Is int callable ? True
Is variable callable ? False
5._
Is student class callable ? True
Is student.greet() callable ? True
Is student instance callable ? False
6._
class student:
   def greet(self):
   print("Hello there")

def __call__(self):
   print("Hello, I am a student.")

std = student()
print("Is student instance callable? ", callable(std))
print(std())
print("Is str callable? ", callable(str)) # str class
print("Is len callable? ", callable(len)) # len
function
print("Is list callable? ", callable(list)) # list class

num = 10
print("Is variable callable? ", callable(num))
Is str callable ? True
Is len callable ? True
Is int callable ? True
Is variable callable ? False
class student:
   def greet(self):
   print("Hello there")

std = student()
print("Is student class callable? ", callable(student))
print("Is student.greet() callable? ", callable(std.greet))
print("Is student instance callable? ", callable(std))
Is student class callable ? True
Is student.greet() callable ? True
Is student instance callable ? False
class student:
   def greet(self):
   print("Hello there")

def __call__(self):
   print("Hello, I am a student.")

std = student()
print("Is student instance callable? ", callable(std))
print(std())

Suggestion : 2

Functions are normal first-class objects in python. The name to with which you define a function object, e.g. with a def statement, is not set in stone, any more than it would be for an int or list. Just as you can do

a = [1, 2, 3]
b = a

to access the elements of a through the name b, you can do the same with functions. In your first example, you could replace

def __call__(self, input1):
   self.my_function(input1)

with the much simpler

__call__ = my_function

Suggestion : 3

Last Updated : 10 Nov, 2017

1._
callable(object)

Output:

True
False

Explanation: The callable() method returns True suggesting that the Geek class is callable, but the instance of Geek is not callable() and it returns a runtime error:

Traceback(most recent call last):
   File "/home/3979dc83032f2d29befe45b6ee6001a4.py", line 10, in
GeekObject()
TypeError: 'Geek'
object is not callable

Suggestion : 4

A Callable object in python is such an object that executes some code on being called instead of raising a TypeError. ,PythonForBeginners.com,What are callable objects in Python?,Python CoursesPython 3 For Beginners

We call any object by placing round brackets after them. For example, When we have to call a function, we place round brackets after them as follows.

def add(num1, num2):
   value = num1 + num2
return value

val = add(10, 20)
print("The sum of {} and {} is {}".format(10, 20, val))
2._
The sum of 10 and 20 is 30

In a similar way, we can also call other callable objects. But, if we call an object that is not callable, the python interpreter will raise the TypeError exception with a message that the object is not callable. This can be observed as follows.

val = 10
val()

If an object does not have  the implementation of the __call__() method in its class definition, it will raise a TypeError exception whenever it is called. This can be seen in the following example.

class Website:
   def __init__(self):
   self.name = "Python For Beginners"

myWebsite = Website()
myWebsite()

Now let us implement the __call__() method in the Website class that prints the address of the website. Observe the output here.

class Website:
   def __init__(self):
   self.name = "Python For Beginners"
def __call__(self, * args, ** kwargs):
   print("Called me?")
print("I am available at pythonforbeginners.com")

myWebsite = Website()
myWebsite()

Suggestion : 5

The callable() method returns True if the object passed appears callable. If not, it returns False.,Here, the object x is not callable. And, the object y appears to be callable (but may not be callable).,The instance of Foo class appears to be callable (and is callable in this case).,The instance of Foo class appears to be callable but it's not callable. The following code will raise an error.

The syntax of callable() is:

callable(object)

Example 1: How callable() works?

x = 5
print(callable(x))

def testFunction():
   print("Test")

y = testFunction
print(callable(y))

Output

False
True

The instance of Foo class appears to be callable (and is callable in this case).

class Foo:
   def __call__(self):
   print('Print Something')

InstanceOfFoo = Foo()

# Prints 'Print Something'
InstanceOfFoo()

Example 3: Object Appears to be Callable but isn't callable.

class Foo:
   def printLine(self):
   print('Print Something')

print(callable(Foo))

Suggestion : 6

Use the Python callable built-in function to check if an object is callable or not.,Summary: in this tutorial, you’ll learn about Python callable objects and how to use the callable function to check if an object is callable.,To check if an object is callable, you can use the built-in function callable:,An object is callable when it can be called using the () operator.

When you can call an object using the () operator, that object is callable:

.wp - block - code {
      border: 0;
      padding: 0;
   }

   .wp - block - code > div {
      overflow: auto;
   }

   .shcb - language {
      border: 0;
      clip: rect(1 px, 1 px, 1 px, 1 px); -
      webkit - clip - path: inset(50 % );
      clip - path: inset(50 % );
      height: 1 px;
      margin: -1 px;
      overflow: hidden;
      padding: 0;
      position: absolute;
      width: 1 px;
      word - wrap: normal;
      word - break: normal;
   }

   .hljs {
      box - sizing: border - box;
   }

   .hljs.shcb - code - table {
      display: table;
      width: 100 % ;
   }

   .hljs.shcb - code - table > .shcb - loc {
      color: inherit;
      display: table - row;
      width: 100 % ;
   }

   .hljs.shcb - code - table.shcb - loc > span {
      display: table - cell;
   }

   .wp - block - code code.hljs: not(.shcb - wrap - lines) {
      white - space: pre;
   }

   .wp - block - code code.hljs.shcb - wrap - lines {
      white - space: pre - wrap;
   }

   .hljs.shcb - line - numbers {
      border - spacing: 0;
      counter - reset: line;
   }

   .hljs.shcb - line - numbers > .shcb - loc {
      counter - increment: line;
   }

   .hljs.shcb - line - numbers.shcb - loc > span {
      padding - left: 0.75 em;
   }

   .hljs.shcb - line - numbers.shcb - loc::before {
      border - right: 1 px solid #ddd;
      content: counter(line);
      display: table - cell;
      padding: 0 0.75 em;
      text - align: right; -
      webkit - user - select: none; -
      moz - user - select: none; -
      ms - user - select: none;
      user - select: none;
      white - space: nowrap;
      width: 1 % ;
   }
object() Code language: Python(python)

To check if an object is callable, you can use the built-in function callable:

callable(object) Code language: Python(python)

All built-in functions are callable. For example, print, len, even callable.

print(callable(print))
print(callable(len))
print(callable(callable)) Code language: Python(python)

All user-defined functions created using def or lambda expressions are callable. For example:

def add(a, b):
   return a + b

print(callable(add)) # True
print(callable(lambda x: x * x)) # TrueCode language: Python(python)

The built-in method such as a_str.upper, a_list.append are callable. For example:

str = 'Python Callable'
print(callable(str.upper)) # TrueCode language: Python(python)

Suggestion : 7

By Bernd Klein. Last modified: 11 Feb 2022.

def the_answer(question):
   return 42
print("the_answer: ", callable(the_answer))
the_answer: True
class FoodSupply:
   def __call__(self):
   return "spam"
foo = FoodSupply()
bar = FoodSupply()
print(foo(), bar())
spam spam
class FoodSupply:
   def __init__(self, * incredients):
   self.incredients = incredients
def __call__(self):
   result = " ".join(self.incredients) + " plus delicious spam!"
return result
f = FoodSupply("fish", "rice")
f()
'fish rice plus delicious spam!'