How to use a global variable in a function in python?
I'm trying to make a lootbox system in python, but I can't use an outside variable inside the function
from main import player
from random import randint
p1 = player
class item:
def lootbox(a,c):
v = 0
b = 0
if c == 'C':
if LbCn < a:
print("Você não tem esse tanto de lootbox comum")
if LbCn >= a:
while v != a:
num = randint(1,10)
inv.append(LbC[num])
LbCn -= 1
print('Você ganhou...')
p1.tempo(1,3)
print(LbC[num])
LbCn -=1
v += 1
inv = []
#Quantas lootboxes o player tem de cada tipo
LbCn = 5
LbRn =0
LbEn = 0
LbLn = 0
#O que se pode ganhar na lootbox comum
LbC = ['Vara de Madeira Podre', 'Isca feita de pão','Anzol Enferrujado','Vara de Madeira','Chapéu de Couro Feio', 'Isca','10 reais','Sanduiche Mofado','Nada!!!','Balde Meio Amassado']
lootbox(1,'C')
0
Author: Bruno Luiz Bender, 2020-03-18
1 answers
You do not need to use global variables (which is not good practice) but rather correctly define the class you built:
from main import player
from random import randint
p1 = player
class Item:
#
# --> crie uma função __init__() e inicialize as variáveis que precisa
#
def __init__(self):
self.inv = []
# Quantas lootboxes o player tem de cada tipo
self.LbCn = 5
...
# O que se pode ganhar na lootbox comum
self.LbC = [
"Vara de Madeira Podre",
...
]
# --> não esqueça de acrescentar o "self" no começo do método.
def lootbox(self, a, c):
v = 0
b = 0
if c == "C":
# --> coloque "self." na frente das variáveis definidas no __init__()
# --> e indica o escopo da classe e não da variável dentro do método.
if self.LbCn < a:
print("Você não tem esse tanto de lootbox comum")
if self.LbCn >= a:
while v != a:
...
# instancie a classe e chame o método desejado.
i = Item()
i.lootbox(1, "C")
And for more details, see the language documentation .
3
Author: Giovanni Nunes, 2020-03-19 01:00:49