简体   繁体   中英

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")

This the full code but what I'm more interested in is

last5 = allgames[-5:]

I want to somehow use this variable in this line of code later on

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

but it wont recognize the variable. Is there any way i can do this?

Your __init__ method should end with this:

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

And then you can use:

await message.channel.send(oqr.last5)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM