我对类/ if语句有这个问题。
我有很多if
语句,看起来像这样:
if message.content.lower().startswith("test"):
time.sleep(1)
await message.add_reaction(gEmoji)
await message.add_reaction(aEmoji)
await message.add_reaction(yEmoji)
但是全部用于不同的单词和表情符号。
这是我的代码的简短版本:
import discord
import random
from discord.ext.commands import Bot
from discord.ext import commands
import sys
import os
import cogs
import config
import logging
import asyncio
import datetime
import time
client = discord.Client()
client = commands.Bot(command_prefix='*')
gEmoji = "🇬"
aEmoji = "🇦"
yEmoji = "🇾"
hEmoji = "🇭"
oEmoji = "🇴"
tEmoji = "🇹"
@client.event
async def on_message(message):
if message.content.lower().startswith("test"):
time.sleep(1)
await message.add_reaction(gEmoji)
await message.add_reaction(aEmoji)
await message.add_reaction(yEmoji)
if message.content.startswith("hot"):
time.sleep(1)
await message.add_reaction(hEmoji)
await message.add_reaction(oEmoji)
await message.add_reaction(tEmoji)
client.run("TOKEN/CENSORED")
在我的这段代码中,我有约200行代码,其中约150行只是if
语句。
由于我是Python的新手,刚开始使用类,所以我想知道是否可以通过某种方式更改if语句以使用类来获得外观更好的代码,以及更易于理解的代码。
如果愿意,您可以使用类,但这对我来说意义不大。有意义的是使用字典和列表:
words = { "gay": [ "🇬", "🇦", "🇾" ],
"hot": [ "🇭", "🇴", "🇹" ]
# add other words as necessary
}
@client.event
async def on_message(message):
for word, emojis in words.items():
if message.content.lower().startswith(word):
time.sleep(1)
for emoji in emojis:
await message.add_reaction(emoji)
这就是整个功能,不需要数百个if
。