How to make class callable python

How to Create Callable Objects in Python: Python OOP Complete Course — Part 20

Learn how to make your class objects callable in Python OOP.

Before we start, let me tell you that:

  • This article is a part of The Complete Course in Object-Oriented Programming in Python, which you can find it here.
  • All resources are available in the “Resources” section below.

Introduction

Have you ever tried to call your class objects??

When you write your Python code, you can usually call your predefined functions and methods, but not your class objects.

It is important to know that in Python you can convert your objects to callable objects. To learn how to do that, keep reading…

Table of Contents

1. What Is a Callable Object?

It is the object that can be called like any other traditional function in Python.

One of the most common use cases of these objects is in deep learning libraries (like PyTorch ) in which data transformation classes objects could be called.
In this case, first, you define an object and initialize it by the required transformation parameters and then you call this object to apply the actual transformation to the data itself.

Читайте также:  What is mysql real escape string in php

2. How to Make an Object Callable

Simply, you make an object callable by overriding the special method __call__() .

__call__(self, arg1, . argn, *args, **kwargs) : This method is like any other normal method in Python. It also can accept positional and arbitrary arguments.
When you define this method inside your class, you are actually defining the behavior for when an object from your class is called. This method returns a value if it is needed.

Источник

4 Examples to Master Python Callable Function

Python Callable

So, today in this article, we will focus on python callable. We will see what python callable means and how can we use it? If you are entirely unaware of the topic, then by the end of this article, you will learn something new by the end of this article. So, let’s get started.

Python Callable() Function

So, first, see what is callable? Yeah, it is simple. Anything which can be called is known as callable. Now the question arises, how does it relate to the python programming language.

So, if you consider a class, then you can say that whenever there is a need for instantiating a class, we need to call the class following the parenthesis. The need for using the parenthesis is to specify that the given class is called, and we have to instantiate an object for it. So, here, we can say that the given class is callable. Now, this goes true for all the classes, whether it is user-defined or inbuilt.

Now the thing that matters to us is that how can we check whether a class or object or a function is callable or not? To do that python callable() function helps us. This function takes the variable as the argument and returns True/False. Now, before moving to the examples, first, see the syntax of the given function.

Syntax

Example 1:- Callable Classes

# Example of Callable Class class MyClass: a = 5 # Checking weather the class is callable or not print(callable(MyClass)) my_object = MyClass() # Calling class to instantiate it's object print(my_object.a)

Similarly, if you consider a function or class method(), then once you define the function, you can call it when needed, and it will do its work. Here, we can also say that functions are callable.

Example 2:- Callable Function

# Example of Callable Function def my_function(): print("This is a callable function") # Checking weather the function is callable or not print(callable(my_function)) my_function() # Calling the function
True This is a callable function

Python make class Callable

So far, so good. I hope both things are known to you. What is more captivating here is that you can also call the object of the class (if mentioned there explicitly). What does that mean? It means that one needs to mention the block of code that handles what happens when an object is called. If it’s mentioned there, then we can say that object of that class is callable.

Now, the question arises how we can do it? To do that, we need to define the __call__ method in the class whose object we want is to be callable. Let’s take an example to understand it more clearly.

Example 3:- Calling a non-callable object

# Example of a non-callable object class MyClass: a = 5 my_object = MyClass() # Calling class to instantiate it's object # Checking whether the object is callable or not print(callable(my_object)) c = my_object() # To check the error
False --------------------------------------------------------------------------- TypeError Traceback (most recent call last) in () 8 # Checking whether the object is callable or not 9 print(callable(my_object)) ---> 10 c = my_object() # To check whether it is callable or not TypeError: 'MyClass' object is not callable

Example 4:- Calling a Callable Object

# Example of a callable object class MyClass: def __call__(self): print('This function is called under call method') my_object = MyClass() # Calling class to instantiate it's object # Checking whether the object is callable or not print(callable(my_object)) c = my_object()
This function is called under call method

FAQs

Yes, it is in-built in python. The function returns True if the method or class is callable. Otherwise False.

Conclusion

So, today in this article, we learned about python callables. We understood the meaning of callable classes, functions, and objects. We saw how an error is raised when a non-callable object is called, and then we saw how we could make an object callable.

I hope this article has helped you. Thank You

Источник

Callable Objects in Python

You might have heard that functions in python are callable objects. In this article, we will discuss what exactly we mean by the term callable object. We will discuss concepts behind the implementation of a callable object and will implement programs to demonstrate the use of callable objects in python.

What is meant by calling an object?

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))

The sum of 10 and 20 is 30

Here, we have called the add() function by passing 10 and 20 as input parameters. The function returns the sum of the input numbers after execution.

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.

Traceback (most recent call last): File "/home/aditya1117/PycharmProjects/pythonProject/webscraping.py", line 2, in val() TypeError: 'int' object is not callable 

Here, you can see that we have defined an integer variable and then we have called it. Upon execution, It raises TypeError exception with a message that “int” object is not callable.

What is the reason that calling a function is okay but calling an integer variable raise exception? Let’s find out.

What are callable objects in Python?

A Callable object in python is such an object that executes some code on being called instead of raising a TypeError.

Every callable object has the __call__() method implemented inside its class definition. If we define callable objects using this detail, then a Callable objects in python are those objects that have an implementation of the __call__() method in their class definition.

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() 
Traceback (most recent call last): File "/home/aditya1117/PycharmProjects/pythonProject/webscraping.py", line 7, in myWebsite() TypeError: 'Website' object is not callable

Here the object myWebsite does not have the implementation of the __call__() method in the definition of its class Website. So, it raises the TypeError exception with a message that the ‘Website’ object is not callable when it is called.

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() 
Called me? I am available at pythonforbeginners.com 

Now, it might be clear to you that we can call any object that has an implementation of the __call__() method in its class definition.

How can we create callable objects in python?

We have seen above that all the callable objects have the implementation of the __call__() method in their class definition. So, To create a callable object in python, we will implement the __call__() method in the function definition of the object as seen in the example given abve.

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() 
Called me? I am available at pythonforbeginners.com 

Conclusion

In this article, we have discussed callable objects in python. We also discussed how we can create a callable object using the __call__() method. To learn more about python programming, you can read this article on list comprehension. You may also like this article on the linked list in Python.

Course: Python 3 For Beginners

Over 15 hours of video content with guided instruction for beginners. Learn how to create real world applications and master the basics.

Источник

Оцените статью