关于python:如何将其作为模块编写?

How to write this as a module?

我想问一下,作为一个Python模块,如何编写以下内容。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
    if message.content.startswith('!guess'):
        # Game Status updating
        now_playing = discord.Game(name='Guessing Game')
        await self.change_status(game=now_playing, idle=False)

        await self.send_message(message.channel, 'Guess a number between 1 to 10')

        def guess_check(m1):
            return m1.content.isdigit()

        guess = await self.wait_for_message(timeout=5.0, author=message.author, check=guess_check)
        answer = random.randint(1, 10)
        if guess is None:
            fmt = 'Sorry, you took too long. It was {}.'
            await self.send_message(message.channel, fmt.format(answer))
            return
        if int(guess.content) == answer:
            await self.send_message(message.channel, 'You are right!')
        else:
            await self.send_message(message.channel, 'Sorry. It is actually {}.'.format(answer))

        # Game Status updating
        now_playing = discord.Game(name='')
        await self.change_status(game=now_playing, idle=False)

这样我就可以使用say guessgame.guess()来调用它。


创建一个名为guessgame.py的python模块文件,然后在其中定义:

1
2
3
4
5
6
"""
This is the module guessgame, it lives in the file guessgame.py
Put some documentation about your module here
"""

def guess(message):
   # Put your code here

然后,从另一个模块(如sample.py或python/ipython shell会话)可以执行以下操作:

1
2
import guessgame
guessgame.guess(message='something')       # What you wanted

RuntimeWarning: coroutine 'guess' was never awaited guessgame.guess()

1
2
3
4
5
# 'await' can only be used inside a coroutine
# if you want guess to be a coroutine, define it like below
async def guess(message):
   # Put your code that uses await
   # Now you can use await expressions

注:

  • 您使用的是await,需要特别注意,请阅读以下内容:https://www.python.org/dev/peps/pep-0492/wait表达式示例
  • 不要在你的guessname.guess()代码中重新定义guess名称,因为你的函数已经被称为guess了,如果你重新定义guess = ...的话,你会被破坏的。
  • 确保您的guessgame.guess()通过了所有必需的参数,仅为了说明目的,我只包括一个参数message
  • 我看到你在代码中使用了self,这意味着这应该是一个类的方法,而不是一个独立的函数?只需要记住一点!