使用装饰器实现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
相关产品推荐
相关产品推荐

