简体   繁体   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")

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:您的__init__方法应以此结尾:

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

And then you can use:然后你可以使用:

await message.channel.send(oqr.last5)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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