Python 提示:TypeError: ‘str’ object is not callable 错误的原因及解决办法
当将字符串值作为函数调用时,Python 会抛出TypeError: 'str' object is not callable
。例如,当str被声明为变量时:
str = 'I am ' # ⚠️ str is no longer pointing to a function
age = 25
# ⛔ Raises TypeError: 'str' object is not callable
print(str + str(age))
Traceback (most recent call last):
File "/tmp/sandbox/test.py", line 5, in
print(str + str(age))
^^^^^^^^
TypeError: 'str' object is not callable
最常见的解决方案是重命名str变量:
代码语言:javascript代码运行次数:0运行复制text = 'I am '
age = 25
print(text + str(age))
# Output: I am 25
什么原因导致 TypeError: 'str' object is not callable
错误?
TypeError : 'str' object is not callable错
误主要发生在以下情况下:
- 将名为str的变量作为参数传递给str()函数。- 如上例所示
- 像调用函数一样调用字符串时 – 声明一个变量,其名称也是函数的名称。
- 调用用@property装饰的方法。
用函数名声明变量
在以下示例中,我们声明一个名为len的变量。在某些时候,当我们调用len()函数来检查输入时,我们会收到错误:
代码语言:javascript代码运行次数:0运行复制len = '' # ⚠️ len is set to an empty string
name = input('Input your name: ')
# ⛔ Raises TypeError: 'str' object is not callable
if (len(name)):
print(f'Welcome, {name}')
为了解决这个问题,我们需要为变量选择一个不同的名称:
代码语言:javascript代码运行次数:0运行复制length = ''
name = input('Input your name: ')
if (len(name)):
print(f'Welcome, {name}')
长话短说,您永远不应该对变量使用函数名称(无论是内置的还是用户定义的)。
调用也是属性名称的方法
当您在类构造函数中定义属性时,任何同名的进一步声明(例如方法)都将被忽略。
代码语言:javascript代码运行次数:0运行复制class Book:
def __init__(self, title):
self.title = title
def title(self):
return self.title
book = Book('Head First Python')
# ⛔ Raises "TypeError: 'str' object is not callable"
print(book.title())
在上面的例子中,由于我们有一个名为title 的属性,因此方法title()被忽略。因此,对title的任何引用都将返回该属性(一个字符串值)。如果你调用title(),你实际上是在尝试调用一个字符串值。
将函数名称改为get_title是一个更安全且更易读的替代方案:
代码语言:javascript代码运行次数:0运行复制class Book:
def __init__(self, title):
self.title = title
def get_title(self):
return self.title
book = Book('Head First Python')
print(book.get_title())
# Output:
Head First Python
调用使用 @property 装饰器修饰的方法
@property装饰器将方法转换为同名只读属性的getter 。
代码语言:javascript代码运行次数:0运行复制class Book:
def __init__(self, title):
self._title = title
@property
def title(self):
"""Get the book price"""
return self._title
book = Book('Head First Python')
# ⛔ Raises "TypeError: 'str' object is not callable"
print(book.title())
您需要访问不带括号的 getter 方法:
代码语言:javascript代码运行次数:0运行复制class Book:
def __init__(self, title):
self._title = title
@property
def title(self):
"""Get the book price"""
return self._title
book = Book('Head First Python')
print(book.title)
# Output:
Head First Python