Search code examples
pythonvariablesmodule

How to passing variables between two modules which have a function?


I stuck, i dont have idea how can I pass the variables to another module.

I have a package with modules:

Game_With_Function_Map.py
Game_informations.py
Game_Variables.py

In Game_Variables.py i have a variable:

floor = 1
moves = 0
moneys = 0

In Game_informations.py :

from game_variable import player_chests, money, floor, moves,

def informations(info):
    if info == "info":
        sorted(player_chests.items(), key=lambda x: x[1], reverse=True)
        print(
            f'\n[Money {money}],\n[Floor {floor}],\n[moves {moves}],\n[Ekwipunek]')

And in main file Game_With_Function_Map.py:

from Game_informations import informations as game_info
from game_variable import player_chests as player_chest
from game_variable import money

This code, change a value in game_variable

    else:
    global money
    player_chest[chest_color] -= 1
    add_gold = draw_money(
        chance_on_money[gold_in_chest[f'{chest_color}']])
    money = money + add_gold
    print('Added', add_gold, 'gold')

After moving variables to game_variable.py all working


Solution

  • you can use class variable property here, where same value is share among all classes instances and if any change happen it happen in all instance

    you can define variable as class instance and use them as it

    code structure: Game_Variables.py file

    class Variables:
        floor = 1
        moves = 0
        money = 0
    

    and you can use these function in other classes or modules as

    from Game_Variables import Variables
    from game_variable import player_chests, money, floor, moves,
    
    def informations(info):
        if info == "info":
            sorted(player_chests.items(), key=lambda x: x[1], reverse=True)
            print(
                f'\n[Money {Variables.money}],\n[Floor {Variables.floor}],\n[moves {Variables.moves}],\n[Ekwipunek]'