代码之家  ›  专栏  ›  技术社区  ›  Geo

使用decorator根据用户回答再次运行python脚本

  •  0
  • Geo  · 技术社区  · 3 年前

    我正在尝试根据用户输入(y/n)再次运行脚本。在我的主文件中,我使用decorator从另一个文件调用了几个函数。我在这里的旧帖子中看到了它的用法,但找不到为什么会出现错误:“ 游戏() TypeError:“NoneType”对象不可调用“

        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")
                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()
    

    我知道这可以用While循环和许多不同的方法来完成,我只想用decorator来完成:/

    1 回复  |  直到 3 年前
        1
  •  2
  •   zaki98    3 年前

    这是因为你 return 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")
        return wrapper
    

    应该有效。