首页 > 解决方案 > 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

我不明白它发生了什么,以及如何解决它。

标签: pythonclosures

解决方案


修复函数的缩进使代码在我的 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 '))

在此处输入图像描述


推荐阅读