【问题标题】:How to stop on_message() in discord.py by using another function?如何使用另一个函数停止 discord.py 中的 on_message()?
【发布时间】:2021-08-08 09:58:19
【问题描述】:

我想使用另一个函数停止一个函数。

def on_message(message):
    #DO WHAT I WANT
    terminate_function(#if condition met)
def terminate_function():
    #terminate_function code

我应该为#terminate_function 代码添加什么?

【问题讨论】:

    标签: python python-3.x discord.py


    【解决方案1】:

    要退出函数,您可以使用return 关键字。

    def on_message(message):
        # do what you want
    
        if "condition met":
            return
    
        print("this is not printed if the condition is met")
    

    【讨论】:

    • 我知道这个方法,但我想把终止函数打破def on_message()。虽然很有帮助
    • 这就是return关键字的用途之一,一遇到就结束函数。
    • 我希望 terminate_function 停止 on_message。
    • 为什么?你没有理由使用另一个功能,你也不能真正做到。
    【解决方案2】:

    你不能让一个函数从另一个函数返回。您可以解决这个问题的方法是让terminate 函数返回bool 并检查。

    def on_message(message):
        #DO WHAT I WANT
        if should_terminate():
            return
    
    def should_terminate() -> bool:
        #DO SOMETHING
        return condition_met  # True if on_message should terminate, False if not
    

    或者,如果您真的希望另一个函数破坏第一个函数,那么一个丑陋的解决方案就是抛出一个错误。

    def on_message(message):
        #DO WHAT I WANT
        terminate_function()
    
    def terminate_function():
        # Raising an exception here will make on_message stop as well
        raise RuntimeError()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-08-10
      • 1970-01-01
      • 1970-01-01
      • 2019-08-23
      • 1970-01-01
      • 2021-10-21
      • 2021-01-17
      相关资源
      最近更新 更多