[英]Can I use classes instead of all these if statements? Discord python bot
我有這個關於類/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)
break
這就是整個函數,不需要數百個if
。 注意:我在假設沒有單詞是另一個單詞的前綴的情況下添加了一個break
來退出外部for
循環,因此例如,如果字典中有“hot”,則字典中沒有“hotter”。 如果這個假設是錯誤的,則應該刪除break
應該將單詞排序為最長優先。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.