TypeError: ‘set’ 对象在 Python 中不可调用
TypeError: ‘set’ object is not callable in Python
Python “TypeError: ‘set’ object is not callable” 发生在我们尝试将 set 对象作为函数调用时,例如通过覆盖内置set()
函数。要解决该错误,请确保您没有覆盖set
并解决函数名和变量名之间的任何冲突。
这是错误如何发生的一个示例。
# 👇️ overriding built-in set() set = set(['a', 'b', 'c']) # ⛔️ TypeError: 'set' object is not callable set(['d', 'e', 'f'])
我们覆盖内置set()
函数,将其设置为一个set
对象,并尝试将其作为函数调用。
要解决该错误,请确保重命名变量并重新启动脚本。
# ✅ Not overriding built-in set() anymore my_set = set(['a', 'b', 'c']) print(set(['d', 'e', 'f'])) # 👉️ {'d', 'f', 'e'}
错误的另一个常见原因是简单地尝试将 aset
作为函数调用。
my_set = {'a', 'b', 'c'} # ⛔️ TypeError: 'set' object is not callable my_set()
要解决该错误,您要么必须删除括号,要么弄清楚如何为变量分配 aset
而不是函数或类。
确保您没有同名的函数和变量。
def example(): return 'hello world' example = {'a', 'b', 'c'} # ⛔️ TypeError: 'set' object is not callable print(example())
example
变量隐藏同名函数,所以当我们尝试调用函数时,我们实际上最终调用了变量。重命名变量或函数可以解决错误。
当我们有一个类方法和一个同名的类属性时,也会导致错误。
class Employee(): def __init__(self, tasks): # 👇️ this attribute hides the method self.tasks = tasks # 👇️ same name as class variable def tasks(self): return self.tasks emp = Employee({'dev', 'test'}) # ⛔️ TypeError: 'set' object is not callable print(emp.tasks())
该类Employee
具有同名的方法和属性。
The attribute hides the method, so when we try to call the method on an instance
of the class, we get the object is not callable error.
To solve the error, you have to rename the class method.
class Employee(): def __init__(self, tasks): self.tasks = tasks def get_tasks(self): return self.tasks emp = Employee({'dev', 'test'}) print(emp.get_tasks()) # 👉️ {'test', 'dev'}
Once you rename the method, you will be able to call it without any issues.
Conclusion #
The Python “TypeError: ‘set’ object is not callable” occurs when we try to
call a set object as a function, e.g. by overriding the built-in set()
function. To solve the error, make sure you’re not overriding set
and resolve
any clashes between function and variable names.