You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用装饰器实现Python脚本重复运行时遇TypeError问题求助

问题解决:装饰器导致的TypeError错误

你的错误根源在于装饰器的返回语句写错了——你写的是return wrapper(),这会直接执行wrapper函数并返回它的结果(也就是None,因为wrapper内部没有返回值),导致被装饰后的game函数变成了None,调用时自然触发TypeError: 'NoneType' object is not callable。

正确的装饰器应该返回wrapper函数本身,而不是调用它的结果。修正后的代码如下:

def restartable(func):
    def wrapper(*args, **kwargs):
        answer = 'y'
        while answer == 'y':
            func(*args, **kwargs)
            while True:
                answer = input("Play Again? y/n")
                if answer in ('y', 'n'):
                    break
                else:
                    print("invalid answer")
    # 直接返回wrapper函数对象,不要加括号调用
    return wrapper

@restartable
def game():
  items = ["X", "Y", "Z"]

  balance = support.get_deposit()

  deposit, balance = support.accept_bet(balance)

  spin_machine = support.spin_machine(items)

  support.matrix_out(spin_machine)

  coef = support.check_col(spin_machine)

  support.calculate_money(balance, deposit, coef)

game()

装饰器的核心作用是给原函数套一层逻辑,因此需要返回包装后的函数对象,而不是执行包装函数的结果。修正后,game会被赋值为wrapper函数,调用game()就能正常触发循环逻辑,根据用户输入的y/n重复运行游戏了。

内容的提问来源于stack exchange,提问作者Geo48

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.27 20:47:43