簡體   English   中英

從 python 中面向 function 的 object 訪問變量

[英]Accesing a variable from an object oriented function in python

import discord
import os
import requests
from bs4 import BeautifulSoup
import lxml
client = discord.Client()
class gamecheck:
    def __init__(self, name):
        if name == "leicester":
            source = requests.get("https://www.11v11.com/teams/arsenal/tab/opposingTeams/opposition/Leicester%20City/")
        elif name == "manutd":
            source = requests.get("https://www.11v11.com/teams/arsenal/tab/opposingTeams/opposition/Manchester%20United/")


        soup = BeautifulSoup(source.text, 'lxml')
        games = soup.find_all(class_="result-status")
        allgames = []

        for game in games:
            allgames.append(game.text)
        last5 = allgames[-5:]
        
oqr = gamecheck("leicester")
utd = gamecheck("manutd")

@client.event
async def on_ready():
    print('We have logged in as {0.user}'.format(client))

@client.event
async def on_message(message):
    if message.author == client.user:
        return
    if message.content.startswith('!history leicester'):
        await message.channel.send("Our last 5 games with this club:")
        await message.channel.send(**last5**)
    elif message.content.startswith('!history manutd'):
        await message.channel.send("Our last 5 games with this club:")
        await message.channel.send(utd)

client.run("token")

這是完整的代碼,但我更感興趣的是

last5 = allgames[-5:]

我想稍后在這行代碼中以某種方式使用這個變量

if message.content.startswith('!history leicester'):
        await message.channel.send("Our last 5 games with this club:")
        await message.channel.send(last5)

但它不會識別變量。 有什么辦法我可以做到這一點?

您的__init__方法應以此結尾:

        for game in games:
            allgames.append(game.text)
        self.last5 = allgames[-5:]

然后你可以使用:

await message.channel.send(oqr.last5)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM