class - How can I have a variable be changed throughout multiple Python modules? -
i've been stuck on trying work hours now. i'm inexperienced programming, i'm sorry if i'm trying ridiculous. if @ possible, avoid creating .txt,.config, or .json (or other file isn't .py) file keep variables simplicity's sake.
i want program have 'experience' variable. throughout game, able add onto variable @ given instance in game in multiple different files. (there around 10 other variables program able use throughout multiple modules). i'm sorry if you've seen me ask similar question today. feel i'm getting close solving error , ends not working. i'm close!
#file1.py experience = 0 file2 import givexp class game: def give_xp(self,given_xp): global experience experience += given_xp print('experience: ',experience) player = game() def main(): print('1) give xp') print('2) give 500 xp') donow = input() if donow == '1': givexp() #this in file2.py if donow == '2': player.give_xp(500) while 1: main()
#file2.py def givexp(): main import player player.give_xp(200)
right issue giving me when press 1 first time program asks me do, nothing happens , asks me again. think because of import statement in file2. when add
if __name__ == '__main__': while 1: main()
this messes program , 2 files have own experience variable, cannot comprehend. i'm aware can change class regular function , have experience returned, in actual game, there going lot more variables keep track of, , other ways having "var1, var2, var3, etc = part_one_of_game()
everything right code works way want to, except pesky bug game asks player or wants twice first time run. there simple fix this?
i think cyclic import not idea because cause layering issue.
it's better move game
class out of __main__
module
as question consider use game
properties store variables keep track of
# game.py class game(object): def __init__(self): self.experience = 0 def give_xp(self,given_xp): self.experience += given_xp print('experience: ',experience) #file2.py def givexp(player): player.give_xp(200) #file1.py game import game player = game() def main(): print('1) give xp') print('2) give 500 xp') donow = input() if donow == '1': givexp(player) #this in file2.py if donow == '2': player.give_xp(500) if __name__ == '__main__': while 1: main()
Comments
Post a Comment