python - TypeError:'int' 对象不可调用。嵌套函数
问题描述
我正在尝试运行这个小型 python 脚本,但在尝试打印时出现错误。
为什么会这样?我该如何解决?代码是:
# Define echo
def echo(n):
"""Return the inner_echo function."""
# Define inner_echo
def inner_echo(word1):
"""Concatenate n copies of word1."""
echo_word = word1 * n
return echo_word
# Return inner_echo
return inner_echo
# Call echo: twice
twice = echo(2)
# Call echo: thrice
thrice = echo(3)
# Call twice() and thrice() then print
print(twice('hello '), thrice('hello '))
但我得到这个错误:
Traceback (most recent call last):
File "<stdin>", line 22, in <module>
print(twice('hello '), thrice('hello '))
TypeError: 'int' object is not callable
但是,如果我这样做:
copy2=twice('Haha ')
我打电话给
copy2
我得到:
In [106]: copy2
Out[106]: 'Haha Haha '
但是,如果我尝试打印它,我会再次收到错误:
In [107]: print(copy2)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
print(copy2)
TypeError: 'int' object is not callable
我不明白它发生了什么,以及如何解决它。
解决方案
修复函数的缩进使代码在我的 IDE 中工作。代码中的函数是一个太靠右的选项卡。下面的代码按预期工作
# Define echo
def echo(n):
"""Return the inner_echo function."""
# Define inner_echo
def inner_echo(word1):
"""Concatenate n copies of word1."""
echo_word = word1 * n
return echo_word
# Return inner_echo
return inner_echo
# Call echo: twice
twice = echo(2)
# Call echo: thrice
thrice = echo(3)
# Call twice() and thrice() then print
print(twice('hello '), thrice('hello '))
推荐阅读
- sap-cloud-sdk - 对函数导入的 VDM 调用返回 null 而不会引发异常
- c# - 如何在 C# 中使用 geckofx 浏览器控件中的代码触发 LauncherDialog.Download 事件?
- reactjs - 无法清除超时 React 功能组件
- r - 使用 R 在 Elasticsearch 中索引数据时出错
- ios - 如何在没有越狱设备的情况下测试越狱措施是否有效
- java - 在调度程序中捕获 Throwable 是一种好习惯吗?
- c# - 请解释这个转换扩展方法
- influxdb - 删除数据库的保留策略,默认为 true。在这种情况下,数据库保留策略会发生什么变化?
- php - Codeigniter 从数据库返回 Null 一个不为空的字段
- amazon-web-services - 我们可以知道 AWS EBS 卷的分离日期吗?