如何将其写为模块?

时间:2016-01-19 19:46:08

标签: python python-3.x

我想问一下,如何在Python中将以下内容编写为模块。

    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)

因此我可以使用说guessgame.guess()

来调用它

1 个答案:

答案 0 :(得分:5)

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

"""
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会话):

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

运行时警告:从未等到过'猜测'猜测.gigg()

# '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/#examples-of-await-expressions
  • 请勿在{{1​​}}代码中重新定义guess名称,因为您的功能已被称为guessname.guess(),如果您重新定义{> {1}}
  • 请确保您的guess已通过所有必需参数,仅用于说明目的我只包含一个参数guess = ...
  • 我看到你在该代码中使用guessgame.guess(),这表明这应该是一个类的方法而不是一个独立的函数?请记住一些事情!