为什么像“str = str(...)”这样的代码会导致 TypeError,但只有第二次?

发布于 2024-11-08 02:49:02 字数 587 浏览 0 评论 0原文

我有一些代码,例如:

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(20

西瓜 2024-11-15 02:49:03

虽然不在您的代码中,但另一个难以发现的错误是在尝试字符串格式化时缺少 % 字符:

"foo %s bar %s coffee"("blah","asdf")

但它应该是:

"foo %s bar %s coffee"%("blah","asdf")

缺少的 % 会导致相同的 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:

"foo %s bar %s coffee"("blah","asdf")

but it should be:

"foo %s bar %s coffee"%("blah","asdf")

The missing % would result in the same TypeError: 'str' object is not callable.

怪异←思 2024-11-15 02:49:03

就我而言,我有一个类,它有一个方法和一个同名的字符串属性,我试图调用该方法,但正在获取字符串属性。

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.

百变从容 2024-11-15 02:49:03

请注意,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.

自演自醉 2024-11-15 02:49:03

如果您有变量 str 并尝试调用 str() 函数,您可能会收到此错误。

You can get this error if you have variable str and trying to call str() function.

冰魂雪魄 2024-11-15 02:49:03

每当发生这种情况时,只需发出以下命令(上面也发布了)

>>> del str

就可以解决它。

Whenever that happens, just issue the following ( it was also posted above)

>>> del str

That should fix it.

飘过的浮云 2024-11-15 02:49:03

另一种情况是:弄乱对象的 __repr__ 函数,其中 format() 调用以非透明方式失败。

在我们的例子中,我们在 __repr__ 上使用了 @property 装饰器,并将该对象传递给 format()。 @property 装饰器导致 __repr__ 对象转换为字符串,然后导致 str 对象不可调用错误。

Another case of this: Messing with the __repr__ function of an object where a format() call fails non-transparently.

In our case, we used a @property decorator on the __repr__ and passed that object to a format(). The @property decorator causes the __repr__ object to be turned into a string, which then results in the str object is not callable error.

梦一生花开无言 2024-11-15 02:49:03

检查您的输入参数,并确保您没有名为 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.

魂归处 2024-11-15 02:49:03
str = 'Hello World String'    
print(str(10)+' Good day!!')

即使我在上面的代码中遇到了这个问题,因为我们正在隐藏 str() 函数。

解决方案是:

string1 = 'Hello World String'
print(str(10)+' Good day!!')
str = 'Hello World String'    
print(str(10)+' Good day!!')

Even I faced this issue with the above code as we are shadowing str() function.

Solution is:

string1 = 'Hello World String'
print(str(10)+' Good day!!')
嘴硬脾气大 2024-11-15 02:49:03

我有同样的错误。就我而言,不是因为名为 str 的变量。但是因为我命名的函数带有str参数并且变量相同。

same_name = same_name(var_name: 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.

same_name = same_name(var_name: str)

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 the str parameter is not present, so it's missing, then it throws that error.

蓝戈者 2024-11-15 02:49:03

尝试调用属性(就好像它是函数一样)也可能会发生此错误:

class Example:
    @property
    def value():
        return 'test'

e = Example()
print(e.value()) # should just be `e.value` to get the string

This error can also occur as a result of trying to call a property (as though it were a function):

class Example:
    @property
    def value():
        return 'test'

e = Example()
print(e.value()) # should just be `e.value` to get the string
小瓶盖 2024-11-15 02:49:03

此问题可能是由以下代码引起的:

"Foo" ("Bar" if bar else "Baz")

您可以通过将字符串文字并排放置来连接它们,例如 "Foo" "Bar"。但是,由于存在左括号,该代码被解释为尝试调用字符串 "Foo",就好像它是一个函数一样。

This problem can be caused by code like:

"Foo" ("Bar" if bar else "Baz")

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.

街角迷惘 2024-11-15 02:49:03

也可能是您尝试以错误的方式建立索引:

a = 'apple'
a(3) ===> 'str' object is not callable

a[3] = l

it could be also you are trying to index in the wrong way:

a = 'apple'
a(3) ===> 'str' object is not callable

a[3] = l
蓝天白云 2024-11-15 02:49:03

建议不要使用 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

满天都是小星星 2024-11-15 02:49:03

此错误也可能发生在以下代码中:

class Shape:
    def __init__(self, colour):
        self.colour = colour
    def colour(self):
        print("colour:", self.colour)

myShape = Shape("pink")
myShape.colour()

__init__ 方法中,我们分配一个属性 colour,该属性与方法 colour 具有相同的名称。当我们稍后尝试调用该方法时,将查找实例的属性。 myShape.colour 是字符串"pink",不可调用。

要解决此问题,请更改方法名称或变量名称。

This error could also occur with code like:

class Shape:
    def __init__(self, colour):
        self.colour = colour
    def colour(self):
        print("colour:", self.colour)

myShape = Shape("pink")
myShape.colour()

In the __init__ method, we assign an attribute colour, which has the same name as the method colour. 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.

心奴独伤 2024-11-15 02:49:03

我也遇到这个错误。
对我来说,这只是一个错字:

我写道:

driver.find_element_by_id("swal2-content").text()

而它应该是:

driver.find_element_by_id("swal2-content").text

I also got this error.
For me it was just a typo:

I wrote:

driver.find_element_by_id("swal2-content").text()

while it should have been:

driver.find_element_by_id("swal2-content").text
妄司 2024-11-15 02:49:03

就我而言,我有一个包含方法的类。该方法没有“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.

我不吻晚风 2024-11-15 02:49:03

FWIW 我只是在一个稍微不同的用例上遇到了这个问题。我一遍又一遍地搜索我的代码,寻找可能使用“str”变量的位置,但找不到它。我开始怀疑我导入的模块之一可能是罪魁祸首......但可惜的是,它是格式化打印语句中缺少的“%”字符。

这是一个例子:

x=5
y=6
print("x as a string is: %s.  y as a string is: %s" (str(x) , str(y)) )

这将导致输出:

   TypeError: 'str' object is not callable

更正是:

x=5
y=6
print("x as a string is: %s.  y as a string is: %s" % (str(x) , str(y)) )

导致我们预期的输出:

x as a string is: 5. y as a string is: 6

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:

x=5
y=6
print("x as a string is: %s.  y as a string is: %s" (str(x) , str(y)) )

This will result in the output:

   TypeError: 'str' object is not callable

The correction is:

x=5
y=6
print("x as a string is: %s.  y as a string is: %s" % (str(x) , str(y)) )

Resulting in our expected output:

x as a string is: 5. y as a string is: 6
终陌 2024-11-15 02:49:03

如果未导入数学库,它也会给出相同的错误,

import math

It also give same error if math library not imported,

import math
过潦 2024-11-15 02:49:03

我意识到这不是运行时警告,但 PyCharm 给了我这个措辞类似的 IDE 警告:

if hasattr(w, 'to_json'):
    return w.to_json()
    # warning, 'str' object is not callable

这是因为 IDE 假定 w.to_json 是一个字符串。解决方案是添加一个 callable() 检查:

if hasattr(w, 'to_json') and callable(w.to_json):
    return w.to_json()

然后警告就消失了。同样的检查还可以防止原始问题中的运行时异常。

I realize this is not a runtime warning, but PyCharm gave me this similarly-worded IDE warning:

if hasattr(w, 'to_json'):
    return w.to_json()
    # warning, 'str' object is not callable

This was because the IDE assumed w.to_json was a string. The solution was to add a callable() check:

if hasattr(w, 'to_json') and callable(w.to_json):
    return w.to_json()

Then the warning went away. This same check may also prevent the runtime exception in the original question.

柒夜笙歌凉 2024-11-15 02:49:02

代码显示:

global str
str = str(parameter)

您正在重新定义 str() 的含义。 str 是字符串类型的内置 Python 名称,您不想更改它。

为局部变量使用不同的名称,并删除 global 语句。

请注意,如果您在 Python REPL 中使用了这样的代码,那么对全局 str 的分配将持续存在,直到您对此采取措施。您可以重新启动解释器,或del str。后者之所以有效,是因为默认情况下 str 实际上不是定义的全局变量 - 相反,它通常在后备中找到(builtins 标准库模块,它是在启动时专门导入的,并被赋予全局名称__builtins__)。

Where the code says:

global str
str = str(parameter)

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, or del str. The latter works because str is not actually a defined global variable by default - instead, it's normally found in a fallback (the builtins standard library module, which is specially imported at startup and given the global name __builtins__).

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文