Python 中TypeError: 'bool' object is not callable 错误
当我们尝试将布尔值(True 或 False)作为函数调用时,会出现 Python“TypeError: 'bool' object is not callable”。 要解决该错误,请更正分配并解决函数名和变量名之间的任何冲突。
看下面的代码
example = True
# ⛔️ TypeError: 'bool' object is not callable
example()
我们必须追踪变量在何处分配了布尔值(True 或 False)并更正对函数或类的分配,或者删除括号。
确保我们没有覆盖内置的 bool()
函数。
# 👇️ overrides built-in bool() function
bool = True
# ⛔️ TypeError: 'bool' object is not callable
print(bool('hello'))
我们覆盖内置的
bool
函数,将其设置为布尔原语,并尝试将其作为函数调用。
要解决该错误,请确保重命名变量并重新启动脚本。
# ✅ Not overriding built-in bool() anymore
my_bool = True
print(bool('hello'))
确保我们没有尝试调用两次返回布尔值的函数。
def is_subscribed():
return True
# ⛔️ TypeError: 'bool' object is not callable
is_subscribed()() # 👈️ remove extra set of parentheses
错误的另一个常见原因是函数和变量同名。
def example():
return 'hello world'
example = True
# ⛔️ TypeError: 'bool' object is not callable
example()
示例变量隐藏了同名函数,因此当我们尝试调用该函数时,我们实际上最终调用了该变量。
重命名变量或函数可以解决错误。
当我们有一个类方法和一个同名的类属性时,也会导致错误。
class Employee():
def __init__(self, is_subscribed):
self.is_subscribed = is_subscribed
# 👇️ same name as class variable
def is_subscribed(self):
return self.is_subscribed
emp = Employee(False)
# ⛔️ TypeError: 'bool' object is not callable
print(emp.is_subscribed())
Employee
类有一个方法和一个同名的属性。
属性隐藏了方法,所以当我们尝试在类的实例上调用方法时,我们得到对象不可调用的错误。
要解决该错误,我们必须重命名类方法。
class Employee():
def __init__(self, is_subscribed):
self.is_subscribed = is_subscribed
def get_is_subscribed(self):
return self.is_subscribed
emp = Employee(False)
print(emp.get_is_subscribed()) # 👉️ False
重命名该方法后,我们将能够毫无问题地调用它。
总结
当我们尝试将布尔值(True
或 False
)作为函数调用时,会出现 Python“TypeError: 'bool' object is not callable”。 要解决该错误,请更正分配并解决函数名和变量名之间的任何冲突。
相关文章
Python pandas.pivot_table() 函数
发布时间:2024/04/24 浏览次数:82 分类:Python
-
Python Pandas pivot_table()函数通过对数据进行汇总,避免了数据的重复。
在 Python 中将 Pandas 系列的日期时间转换为字符串
发布时间:2024/04/24 浏览次数:894 分类:Python
-
了解如何在 Python 中将 Pandas 系列日期时间转换为字符串
在 Python Pandas 中使用 str.split 将字符串拆分为两个列表列
发布时间:2024/04/24 浏览次数:1124 分类:Python
-
本教程介绍如何使用 pandas str.split() 函数将字符串拆分为两个列表列。
在 Pandas 中将 Timedelta 转换为 Int
发布时间:2024/04/23 浏览次数:231 分类:Python
-
可以使用 Pandas 中的 dt 属性将 timedelta 转换为整数。
Python 中的 Pandas 插入方法
发布时间:2024/04/23 浏览次数:112 分类:Python
-
本教程介绍了如何在 Pandas DataFrame 中使用 insert 方法在 DataFrame 中插入一列。
使用 Python 将 Pandas DataFrame 保存为 HTML
发布时间:2024/04/21 浏览次数:106 分类:Python
-
本教程演示如何将 Pandas DataFrame 转换为 Python 中的 HTML 表格。
如何将 Python 字典转换为 Pandas DataFrame
发布时间:2024/04/20 浏览次数:73 分类:Python
-
本教程演示如何将 python 字典转换为 Pandas DataFrame,例如使用 Pandas DataFrame 构造函数或 from_dict 方法。
如何在 Pandas 中将 DataFrame 列转换为日期时间
发布时间:2024/04/20 浏览次数:101 分类:Python
-
本文介绍如何将 Pandas DataFrame 列转换为 Python 日期时间。