Callable() fruncion in Python

Function Name:

callable()

 

Function Signature:

callable(object)

 

Function Overview:

The function callable() determines whether a Python object is a callable object or not. It returns True if the object is callable and False if the object is not callable.

The following are callable in Python:

  • A function

 

  • A class; Calling a class creates a new instance of the class

 

  • An object; an object is callable in python.

   

Example 1:

def Function1():

    pass

 

class Mouse:

    def move(self):

        print("Moving")

 

    def __call__(self,p):

        print("calling a mouse object")

 

       

listObject = [1,2,3,4,5]

 

# Check a list is callable

print("Is a list callable:{}".format(callable(listObject)))

 

# Check an immutable sequence of bytes is callable

bytesObject = bytes("Sample Text", "utf-8")

print("Is a bytes instance callable:{}".format(callable(bytesObject)))

 

# Check a function is callable

print("Is a function callable:{}".format(callable(Function1)))

 

# Check a class is callable

print("Is a class callable:{}".format(callable(Mouse)))

 

# Check an object implementing __call__() is callable

mouse1 = Mouse()

print("Is an object implementing the __call__() callable:{}".format(callable(mouse1)))

 

Output:

Is a list callable:False

Is a bytes instance callable:False

Is a function callable:True

Is a class callable:True

Is an object implementing the __call__() callable:True

Example 2:

class Date:

    @staticmethod

    def initdate():

        print("initing")

   

    def move(self):

        print("moving")

       

# Is the move() instance method callable

dateInstance = Date()

print("Is an instance method callable:{}".format(callable(dateInstance.move)))

 

# Is a class method callable

print("Is a class method callable:{}".format(callable(dateInstance.initdate)))

 

Output:

 

Is an instance method callable:True

Is a class method callable:True

 


Copyright 2024 © pythontic.com