Home > Enterprise >  How to use a variable in another function without making it global?
How to use a variable in another function without making it global?

Time:08-09

(Py file) So, I am trying to make two commands for a discord bot and in 1 command it makes 3 variables. but I need to use those in another command. it's a Pokémon bot and in the first command it makes 3 random variables code1 part2 of code1

and so, I need those starter variables in another command called pick_(pokemon name)

 await ctx.channel.send (f'Your Starters are... {starterchoice1}, {starterchoice2} and {starterchoice3}. type .pick_The pokemons name to pick')

and I need the variables in this code, so it knows what starters he has to pick from. I have tried storing the variable value in a JSON file, but I knew there has to be an easier and better way.

CodePudding user response:

If you return the values from the first function directly into the second, it would look similar to this

def pick(poke_list):
  # Do things
  return starterchoice1, starterchoice2, starterchoice3


def send(starterchoice1, starterchoice2, starterchoice3):
  print(f'Your Starters are... {starterchoice1}, {starterchoice2} and {starterchoice3}. type .pick_The pokemons name to pick')
  return value

pick1, pick2, pick3 = pick(poke_list)
value = send(pick1, pick2, pick3)

CodePudding user response:

If the two commands are in the same class as where you're instanciating those variables you can use self to refer to the variable.

Why do I need to use "self" to reference the class variable in a class method?

So if you had

Class PokemonSelection():
    starterchoice1 = "Squirtle"
    starterchoice2 = "Treecko"
    starterchoice3 = "Rowlet"
def print_start_choices(self):
    print(f'Your Starters are... {self.starterchoice1}, {self.starterchoice2} and {self.starterchoice3}')
  • Related