为什么像“str = str(...)”这样的代码会导致 TypeError,但只有第二次?
我有一些代码,例如:
def example(parameter):
global str
str = str(parameter)
print(str)
example(1)
example(2)
第一次调用 example
有效,但第二次我收到一个错误,例如:
Traceback (most recent call last):
File "test.py", line 7, in <module>
example(2)
File "test.py", line 3, in example
str = str(parameter)
TypeError: 'str' object is not callable
为什么会发生这种情况,如何修复它?
如果您在交互式会话中遇到此类问题,并且希望在不重新启动解释器的情况下解决该问题,请参阅如何恢复我不小心覆盖的内置函数?.
I have some code like:
def example(parameter):
global str
str = str(parameter)
print(str)
example(1)
example(2)
The first call to example
works, but then the second time around I get an error like:
Traceback (most recent call last):
File "test.py", line 7, in <module>
example(2)
File "test.py", line 3, in example
str = str(parameter)
TypeError: 'str' object is not callable
Why does this happen, and how can I fix it?
If you are in an interactive session and encountered a problem like this, and you want to fix the problem without restarting the interpreter, see How to restore a builtin that I overwrote by accident?.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(20)
虽然不在您的代码中,但另一个难以发现的错误是在尝试字符串格式化时缺少
%
字符:但它应该是:
缺少的
%
会导致相同的TypeError: 'str' object is not callable
。While not in your code, another hard-to-spot error is when the
%
character is missing in an attempt of string formatting:but it should be:
The missing
%
would result in the sameTypeError: 'str' object is not callable
.就我而言,我有一个类,它有一个方法和一个同名的字符串属性,我试图调用该方法,但正在获取字符串属性。
In my case I had a class that had a method and a string property of the same name, I was trying to call the method but was getting the string property.
请注意,
TypeError: 'str' object is not callable
仅表示尝试调用(即,使用函数调用语法)字符串(即,之前分配有字符串的任何名称)它)。使用任何其他内置方法作为变量名可能会导致完全相同的错误消息。Note that
TypeError: 'str' object is not callable
means only that there is an attempt to call (i.e., use function-call syntax) a string (i.e., any name that previously had a string assigned to it). Using any other built-in method as variable name can cause the exact same error message.如果您有变量
str
并尝试调用str()
函数,您可能会收到此错误。You can get this error if you have variable
str
and trying to callstr()
function.每当发生这种情况时,只需发出以下命令(上面也发布了)
就可以解决它。
Whenever that happens, just issue the following ( it was also posted above)
That should fix it.
另一种情况是:弄乱对象的 __repr__ 函数,其中
format()
调用以非透明方式失败。在我们的例子中,我们在
__repr__
上使用了@property
装饰器,并将该对象传递给format()
。 @property 装饰器导致 __repr__ 对象转换为字符串,然后导致 str 对象不可调用错误。Another case of this: Messing with the
__repr__
function of an object where aformat()
call fails non-transparently.In our case, we used a
@property
decorator on the__repr__
and passed that object to aformat()
. The@property
decorator causes the__repr__
object to be turned into a string, which then results in thestr
object is not callable error.检查您的输入参数,并确保您没有名为
type
的参数。如果是这样,那么您将发生冲突并收到此错误。Check your input parameters, and make sure you don't have one named
type
. If so then you will have a clash and get this error.即使我在上面的代码中遇到了这个问题,因为我们正在隐藏
str()
函数。解决方案是:
Even I faced this issue with the above code as we are shadowing
str()
function.Solution is:
我有同样的错误。就我而言,不是因为名为
str
的变量。但是因为我命名的函数带有str参数并且变量相同。我循环运行它。第一次运行没问题。我第二次遇到这个错误。将变量重命名为与函数名称不同的名称修复了此问题。所以我认为这是因为Python一旦在作用域中关联了一个函数名称,第二次尝试将左侧部分(
same_name =
)关联为对函数的调用,并检测到str< /code> 参数不存在,因此丢失,然后抛出该错误。
I had the same error. In my case wasn't because of a variable named
str
. But because I named a function with a str parameter and the variable the same.I run it in a loop. The first time it run ok. The second time I got this error. Renaming the variable to a name different from the function name fixed this. So I think it's because Python once associate a function name in a scope, the second time tries to associate the left part (
same_name =
) as a call to the function and detects that thestr
parameter is not present, so it's missing, then it throws that error.尝试调用属性(就好像它是函数一样)也可能会发生此错误:
This error can also occur as a result of trying to call a property (as though it were a function):
此问题可能是由以下代码引起的:
您可以通过将字符串文字并排放置来连接它们,例如
"Foo" "Bar"
。但是,由于存在左括号,该代码被解释为尝试调用字符串"Foo"
,就好像它是一个函数一样。This problem can be caused by code like:
You can concatenate string literals by putting them next to each other, like
"Foo" "Bar"
. However, because of the open parenthesis, the code was interpreted as an attempt to call the string"Foo"
as if it were a function.也可能是您尝试以错误的方式建立索引:
it could be also you are trying to index in the wrong way:
建议不要使用
str
int
list
等作为变量名,尽管 python 允许这样做。这是因为在尝试访问命名相同的保留关键字时可能会造成此类事故
it is recommended not to use
str
int
list
etc.. as variable names, even though python will allow it.this is because it might create such accidents when trying to access reserved keywords that are named the same
此错误也可能发生在以下代码中:
在
__init__
方法中,我们分配一个属性colour
,该属性与方法colour
具有相同的名称。当我们稍后尝试调用该方法时,将查找实例的属性。myShape.colour
是字符串"pink"
,不可调用。要解决此问题,请更改方法名称或变量名称。
This error could also occur with code like:
In the
__init__
method, we assign an attributecolour
, which has the same name as the methodcolour
. When we later attempt to call the method, the instance's attribute is looked up instead.myShape.colour
is the string"pink"
, which is not callable.To fix this, change either the method name or the variable name.
我也遇到这个错误。
对我来说,这只是一个错字:
我写道:
而它应该是:
I also got this error.
For me it was just a typo:
I wrote:
while it should have been:
就我而言,我有一个包含方法的类。该方法没有“self”作为第一个参数,当我调用该方法时抛出错误。一旦我将“self”添加到方法的参数列表中,就很好了。
In my case, I had a Class with a method in it. The method did not have 'self' as the first parameter and the error was being thrown when I made a call to the method. Once I added 'self,' to the method's parameter list, it was fine.
FWIW 我只是在一个稍微不同的用例上遇到了这个问题。我一遍又一遍地搜索我的代码,寻找可能使用“str”变量的位置,但找不到它。我开始怀疑我导入的模块之一可能是罪魁祸首......但可惜的是,它是格式化打印语句中缺少的“%”字符。
这是一个例子:
这将导致输出:
更正是:
导致我们预期的输出:
FWIW I just hit this on a slightly different use case. I scoured and scoured my code looking for where I might've used a 'str' variable, but could not find it. I started to suspect that maybe one of the modules I imported was the culprit... but alas, it was a missing '%' character in a formatted print statement.
Here's an example:
This will result in the output:
The correction is:
Resulting in our expected output:
如果未导入数学库,它也会给出相同的错误,
It also give same error if math library not imported,
我意识到这不是运行时警告,但 PyCharm 给了我这个措辞类似的 IDE 警告:
这是因为 IDE 假定
w.to_json
是一个字符串。解决方案是添加一个callable()
检查:然后警告就消失了。同样的检查还可以防止原始问题中的运行时异常。
I realize this is not a runtime warning, but PyCharm gave me this similarly-worded IDE warning:
This was because the IDE assumed
w.to_json
was a string. The solution was to add acallable()
check:Then the warning went away. This same check may also prevent the runtime exception in the original question.
代码显示:
您正在重新定义
str()
的含义。str
是字符串类型的内置 Python 名称,您不想更改它。为局部变量使用不同的名称,并删除
global
语句。请注意,如果您在 Python REPL 中使用了这样的代码,那么对全局
str
的分配将持续存在,直到您对此采取措施。您可以重新启动解释器,或del str
。后者之所以有效,是因为默认情况下str
实际上不是定义的全局变量 - 相反,它通常在后备中找到(builtins
标准库模块,它是在启动时专门导入的,并被赋予全局名称__builtins__
)。Where the code says:
You are redefining what
str()
means.str
is the built-in Python name of the string type, and you don't want to change it.Use a different name for the local variable, and remove the
global
statement.Note that if you used code like this at the Python REPL, then the assignment to the global
str
will persist until you do something about it. You can restart the interpreter, ordel str
. The latter works becausestr
is not actually a defined global variable by default - instead, it's normally found in a fallback (thebuiltins
standard library module, which is specially imported at startup and given the global name__builtins__
).