TypeError: 'str' object is not callable (Python)

后端 未结 16 1137
忘了有多久
忘了有多久 2020-11-22 11:44

Code:

import urllib2 as u
import os as o
inn = \'dword.txt\'
w = open(inn)
z = w.readline()
b = w.readline()
c = w.readline()
x = w.readline         


        
相关标签:
16条回答
  • 2020-11-22 11:51

    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.

    0 讨论(0)
  • 2020-11-22 11:53

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

    0 讨论(0)
  • 2020-11-22 11:53

    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.

    0 讨论(0)
  • 2020-11-22 11:53

    I got this warning from an incomplete method check:

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

    It 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):
    

    Then the warning went away.

    0 讨论(0)
  • 2020-11-22 11:53

    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

    0 讨论(0)
  • 2020-11-22 11:54

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

    >>> del str
    

    That should fix it.

    0 讨论(0)
提交回复
热议问题