Python class is not callable

Решение ошибки TypeError: ‘module’ object is not callable в Python

В процессе работы с Python иногда возникает ошибка «TypeError: ‘module’ object is not callable». Эта ошибка обычно происходит, когда разработчик пытается вызвать модуль, как функцию.

Пример ошибки:

import math result = math(5)

В этом коде разработчик пытается вызвать модуль math как функцию, что невозможно и вызывает ошибку TypeError: ‘module’ object is not callable .

Причина ошибки:

Модули в Python — это файлы, содержащие Python код, которые можно импортировать в другие Python файлы. Они не являются функциями и не могут быть вызваны как функции. Вместо этого, модули предоставляют функции, переменные и классы, которые можно использовать в другом коде после импорта модуля.

Решение ошибки:

Для решения этой ошибки необходимо вызвать функцию, класс или переменную из модуля, а не сам модуль. В приведенном выше примере, если был импортирован модуль math , следует вызвать функцию из этого модуля, а не сам модуль.

Читайте также:  Python медленнее чем c

Исправленный пример:

import math result = math.sqrt(5)

В этом коде вызывается функция sqrt() из модуля math , а не сам модуль math . Этот код не вызовет ошибку TypeError: ‘module’ object is not callable , так как вызывается функция, а не модуль.

В заключение, ошибка «TypeError: ‘module’ object is not callable» в Python обычно указывает на то, что разработчик пытается вызвать модуль, как функцию. Для решения этой ошибки необходимо вызвать функцию, класс или переменную из модуля, а не сам модуль.

Источник

Python Class Object Is Not Callable

A callable object in Python is an object that can be called – explicitly initiated to execute. If we attempt to call a not-callable function, we run into this kind TypeError message.

In Python, objects are called by passing arguments in parentheses. For example, a callable object x can be called as x(arg1, arg2, …) or using the method __call__() as x.__call__(arg1, arg2, …). By the way, Python methods starting and ending with double underscores, like __call__(), are special functions called magic or dunder methods.

Knowing if an Object is Callable

One can verify if a Python object is callable using the callable() function. Let’s create some objects in Python and check if they are callable.

From these examples, we can see that integers, strings, and lists are not callable, but functions and classes are. In fact, all data types are not callable.

Let’s attempt to call an object that is not callable to reproduce the object is not a callable error.

TypeError: 'list' object is not callable

The above mistake often happens when we attempt to access the value of the list at index 2 by using parenthesis (calling the list) instead of using square brackets b_list[2] for list indexing.

TypeError: Class Object is not Callable

In the earlier section, we said class objects are callable. That is a fact, of course, but that is contingent on how you call the class object you are trying to use. This section will discuss how to reproduce this error and how to solve it.

Reproducing Class Object is not a Callable Error

Consider a module and a main script in the same folder. A module in Python is simply a Python file with variables, functions, or classes that can be imported and used in another script – calling it the main script here.

Module: ClassExample.py

Main script: main_script.py

TypeError: 'MyClass1' object is not callable

Executing the main_script.py file leads to a Class object that is not callable. This error is caused by the module’s line MyClass1 = MyClass1(). In this line, the class MyClass1() is initialized with a variable of the same name. The call of the MyClass1 class again in the main script, which has already been initialized in the module, is like calling MyClass1()(), which leads to the error.

The solution is to initialize the class with a different name in the module script or remove that line altogether and call the class in the main script.

TypeError: Module object is not callable

This error occurs when module importation is not done incorrectly. The example below shows the importation problem caused when a module has the same name as the class being called in the main script.

Module: ClassExample1.py

Источник

Python TypeError: Object is Not Callable. Why This Error?

Python object is not callable

Have you ever seen the TypeError object is not callable when running one of your Python programs? We will find out together why it occurs.

The TypeError object is not callable is raised by the Python interpreter when an object that is not callable gets called using parentheses. This can occur, for example, if by mistake you try to access elements of a list by using parentheses instead of square brackets.

I will show you some scenarios where this exception occurs and also what you have to do to fix this error.

What Does Object is Not Callable Mean?

To understand what “object is not callable” means we first have understand what is a callable in Python.

As the word callable says, a callable object is an object that can be called. To verify if an object is callable you can use the callable() built-in function and pass an object to it. If this function returns True the object is callable, if it returns False the object is not callable.

Let’s test this function with few Python objects…

Lists are not callable

>>> numbers = [1, 2, 3] >>> callable(numbers) False

Tuples are not callable

>>> numbers = (1, 2, 3) >>> callable(numbers) False

Lambdas are callable

Functions are callable

>>> def calculate_sum(x, y): . return x+y . >>> callable(calculate_sum) True

A pattern is becoming obvious, functions are callable objects while data types are not. And this makes sense considering that we “call” functions in our code all the time.

What Does TypeError: ‘int’ object is not callable Mean?

In the same way we have done before, let’s verify if integers are callable by using the callable() built-in function.

>>> number = 10 >>> callable(number) False

As expected integers are not callable 🙂

So, in what kind of scenario can this error occur with integers?

Create a class called Person. This class has a single integer attribute called age.

class Person: def __init__(self, age): self.age = age

Now, create an object of type Person:

Below you can see the only attribute of the object:

Let’s say we want to access the value of John’s age.

For some reason the class does not provide a getter so we try to access the age attribute.

>>> print(john.age()) Traceback (most recent call last): File "callable.py", line 6, in print(john.age()) TypeError: 'int' object is not callable

The Python interpreter raises the TypeError exception object is not callable.

That’s because we have tried to access the age attribute with parentheses.

The TypeError ‘int’ object is not callable occurs when in the code you try to access an integer by using parentheses. Parentheses can only be used with callable objects like functions.

What Does TypeError: ‘float’ object is not callable Mean?

The Python math library allows to retrieve the value of Pi by using the constant math.pi.

I want to write a simple if else statement that verifies if a number is smaller or bigger than Pi.

import math number = float(input("Please insert a number: ")) if number < math.pi(): print("The number is smaller than Pi") else: print("The number is bigger than Pi")
Please insert a number: 4 Traceback (most recent call last): File "callable.py", line 12, in if number < math.pi(): TypeError: 'float' object is not callable

Interesting, something in the if condition is causing the error ‘float’ object is not callable.

That’s because math.pi is a float and to access it we don’t need parentheses. Parentheses are only required for callable objects and float objects are not callable.

The TypeError ‘float’ object is not callable is raised by the Python interpreter if you access a float number with parentheses. Parentheses can only be used with callable objects.

What is the Meaning of TypeError: ‘str’ object is not callable?

The Python sys module allows to get the version of your Python interpreter.

>>> import sys >>> print(sys.version()) Traceback (most recent call last): File "", line 1, in TypeError: 'str' object is not callable

No way, the object is not callable error again!

To understand why check the official Python documentation for sys.version.

Python sys version

We have added parentheses at the end of sys.version but this object is a string and a string is not callable.

The TypeError ‘str’ object is not callable occurs when you access a string by using parentheses. Parentheses are only applicable to callable objects like functions.

Error ‘list’ object is not callable when working with a List

Define the following list of cities:

>>> cities = ['Paris', 'Rome', 'Warsaw', 'New York']

Now access the first element in this list:

>>> print(cities(0)) Traceback (most recent call last): File "", line 1, in TypeError: 'list' object is not callable

By mistake I have used parentheses to access the first element of the list.

To access an element of a list the name of the list has to be followed by square brackets. Within square brackets you specify the index of the element to access.

So, the problem here is that instead of using square brackets I have used parentheses.

The TypeError ‘list’ object is not callable occurs when you access an item of a list by using parentheses. Parentheses are only applicable to callable objects like functions. To access elements in a list you have to use square brackets instead.

Error ‘list’ object is not callable with a List Comprehension

When working with list comprehensions you might have also seen the “object is not callable” error.

This is a potential scenario when this could happen.

I have created a list of lists variable called matrix and I want to double every number in the matrix.

>>> matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] >>> [[2*row(index) for index in range(len(row))] for row in matrix] Traceback (most recent call last): File "", line 1, in File "", line 1, in File "", line 1, in TypeError: 'list' object is not callable

This error is more difficult to spot when working with list comprehensions as opposed as when working with lists.

That’s because a list comprehension is written on a single line and includes multiple parentheses and square brackets.

If you look at the code closely you will notice that the issue is caused by the fact that in row(index) we are using parentheses instead of square brackets.

>>> [[2*row[index] for index in range(len(row))] for row in matrix] [[2, 4, 6], [8, 10, 12], [14, 16, 18]]

Conclusion

Now that we went through few scenarios in which the error object is not callable can occur you should be able to fix it quickly if it occurs in your programs.

I hope this article has helped you save some time! 🙂

I’m a Software Engineer and Programming Coach. I want to help you in your journey to become a Super Developer!

Источник

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