Python 我使用input、map和int geves me的最基本的代码”;类型错误:';str';对象不可调用";
我在GoogleCollab中使用此代码询问用户输入日期 但在执行代码时,我得到 TypeError:“str”对象不可调用Python 我使用input、map和int geves me的最基本的代码”;类型错误:';str';对象不可调用";,python,datetime,typeerror,Python,Datetime,Typeerror,我在GoogleCollab中使用此代码询问用户输入日期 但在执行代码时,我得到 TypeError:“str”对象不可调用 我没有调用任何字符串,有什么问题吗?代码是正确的。这是缩进的问题。 Python有几个函数(int,input,map,list,set,dict,min,…)可以在代码中使用 这些函数的名称不受保护,无法以其他方式使用。但是,将它们用作变量名会隐藏原始函数,使其无法访问 这样做会导致此类错误消息 演示: 输出: The 'int' function was overwr
我没有调用任何字符串,有什么问题吗?代码是正确的。这是缩进的问题。
Python有几个函数(
int
,input
,map
,list
,set
,dict
,min
,…)可以在代码中使用
这些函数的名称不受保护,无法以其他方式使用。但是,将它们用作变量名会隐藏原始函数,使其无法访问
这样做会导致此类错误消息
演示:
输出:
The 'int' function was overwritten to be a string
Enter date: 2021,2,2
'str' object is not callable
The 'map' function was overwritten to be a string
Enter date: 2021,2,2
'str' object is not callable
The 'input' function was overwritten to be a string
'str' object is not callable
The 'datetime' function was overwritten to be a string
Enter date: 2021,2,2
'str' object is not callable
您的代码非常好,它不会触发任何您可能为字符串指定的
input
或map
错误。检查前面几行,避免使用Python内置变量名。我认为缩进只是不正确的复制粘贴。不正确的缩进不会导致OP提到的“TypeError:'str'对象不可调用”。
from datetime import datetime
# store the original functions under different name for restoring them later
old_int = int
old_map = map
old_input = input
old_dt = datetime
for what in ["int", "map", "input", "datetime"]:
# restore original functions to their names
int, map, input, datetime = old_int, old_map, old_input, old_dt
# set current function to be a string
if what == "int":
int = "some string"
elif what == "map":
map = "some string"
elif what == "input":
input = "some string"
else:
datetime = "some string"
print(f"The '{what}' function was overwritten to be a string")
# try to use the overwritten function and print the error message if it happens
try:
date_entry = input('Enter date: ')
year, month, day = map(int, date_entry.split(','))
date = datetime(year, month, day)
except Exception as e:
print(e, "\n")
The 'int' function was overwritten to be a string
Enter date: 2021,2,2
'str' object is not callable
The 'map' function was overwritten to be a string
Enter date: 2021,2,2
'str' object is not callable
The 'input' function was overwritten to be a string
'str' object is not callable
The 'datetime' function was overwritten to be a string
Enter date: 2021,2,2
'str' object is not callable