【问题标题】:'str' object is not callable during running the code'str' 对象在运行代码期间不可调用
【发布时间】:2019-08-22 09:25:58
【问题描述】:

在运行下面的代码时,我收到了错误消息:

"TypeError: 'str' 对象不可调用"

据我了解,当我尝试通过 print 调用“str”且不可调用的对象(与函数不同)时,就会出现问题。当我将 print(text()) 行修改为 print(text) 时,代码运行良好。所以,作为一个python初学者,我很好奇,为什么会这样,因为我正在调用函数,同时返回str。?

    def decor(func):
        x = "="
        return x + func() + x
    @decor
    def text():
        return "test"
    print(text())

我希望结果是 =test=。从我的角度来看,我调用了函数text(),它返回str值“test”。函数text() 被装饰了一个,所以在调用text() 后,由于装饰器和装饰器的字符串连接,我必须看到输出:=test=,但实际输出是:

Traceback (most recent call last):
  File "test.py", line 7, in <module>
    print(text())
TypeError: 'str' object is not callable'

【问题讨论】:

    标签: python-3.x


    【解决方案1】:

    装饰器函数的返回应该是一个可调用的。所以在这种情况下 return 应该是一个函数。

    以下将起作用

    def decor(func):
        def wrapfunc():
            x = "="
            return x + func() + x
    
        return wrapfunc
    
    @decor
    def text():
        return "test"
    
    print(text())
    

    【讨论】:

      【解决方案2】:

      您的装饰器功能不正确。你需要让它里面有一个wrapper

      def decor(func):
          def wrapper():
              x = "="
              return x + func() + x
          return wrapper
      
      @decor
      def text():
          return "test"
      
      text()
      '=test='
      

      【讨论】:

        猜你喜欢
        • 2023-03-26
        • 2022-01-08
        • 2019-04-14
        • 1970-01-01
        • 1970-01-01
        • 2015-03-07
        • 2011-06-07
        • 2019-03-05
        相关资源
        最近更新 更多