2016-08-04 155 views
0

我對Python非常陌生,所以我很抱歉如果這是一個簡單的問題,我正在創建一個程序,我需要跨多個文件共享一個全局變量。我有一個叫settings.py文件看起來像這樣:跨多個文件共享全局

def init(): 
    global BACKPACK 
    global SURVIVAL_TOOLS 

    BACKPACK = {} 
    SURVIVAL_TOOLS = {} 

import這些設置成稱爲battle.pyprepare.py另一個文件:

from settings import init 
# battle.py # 
def win_battle(animal): 
    print "You do one final slash and the {} goes limp." \ 
      " You pick it up and start walking back to camp.".format(animal) 
    init.SURVIVAL_TOOLS['meat'] = 1 
    if 'camp' in init.SURVIVAL_TOOLS: 
     return_to_camp() 
    else: 
     options = ['create a fire', 'create a camp'] 
     for opt in options: 
      print "TEST" # TODO: FINISH THIS METHOD 

from settings import init 

def gather_gear(player): 
    # prepare.py # 
    """ 
    Gather your gear from a set list of items you have available 
    :type player: String 
    """ 
    print formatter() 
    print "{}! Shouts Jack as he runs towards you." \ 
      " Do you wanna go Hiking this weekend?" \ 
      " You ponder this for a second." \ 
      " What the hell, you think." \ 
      " Can't be any worse then last time." \ 
      " Sure, Jack! You say enthusiastically." \ 
      " Just let me get some things prepared.\n".format(player) 

    options = { # All the items that are available to you before you leave 
     'fire starter': 1, 
     'matches': randint(1, 5), # Uses random integers as the value 
     'flash light': 1, 
     'sleeping bag': 1, 
     'canteen cup': 1, 
     'dried foods': randint(2, 6), 
     'shovel': 1, 
     'knife': 1, 
     'pair of socks': randint(2, 10), 
     'granola bars': randint(2, 5), 
     'machete': 1, 
     'bottle of whiskey': 1, 
     'heavy jacket': 1, 
     'tinder pieces': randint(3, 5) 
    } 

    for key in options: 
     print "You have {} {}".format(options[key], key) # Print out all your items and make it look pretty 

    count = 3 
    num_in_pack = 0 
    print '\n' 
    while count != 0: 
     item = raw_input("What would you like to take with you? Choose {} items one at a time: ".format(str(count))).lower() 
     if item in options and item not in init.BACKPACK: # As long as the item is available you can use it 
      init.BACKPACK[item] = options[item] # Add the item value to your backpack constant 
      count -= 1 
      print "You throw a {} in your backpack".format(item) 
      num_in_pack += 1 
      if num_in_pack == 3: # If you have three items, lets begin! 
       print "Your backpack is now full." 
       start_adventure(player) 
     else: 
      print "Can't bring that item." 

    return init.BACKPACK 

但是我得到了一個警告我IDE即:

Cannot find reference 'SURVIVAL_TOOLS' in 'function' less... (Ctrl+F1 Alt+T) This inspection detects names that should resolve but don't. Due to dynamic dispatch and duck typing, this is possible in a limited but useful number of cases. Top-level and class-level items are supported better than instance items.

,並運行該程序時,我得到:

Traceback (most recent call last): 
    File "game.py", line 1, in <module> 
    from prepare import * 
    File "C:\Users\thomas_j_perkins\bin\python\game\prepare.py", line 1, in <modul 
e> 
    from game import * 
    File "C:\Users\thomas_j_perkins\bin\python\game\game.py", line 2, in <module> 
    from choices import * 
    File "C:\Users\thomas_j_perkins\bin\python\game\choices.py", line 3, in <modul 
e> 
    from prepare import BACKPACK 
ImportError: cannot import name BACKPACK 

我得到了我所有的常量從這個question

所以移動到單個文件的想法,我的問題是,爲什麼我無法使用我在settings.py文件中創建的常量變量?


編輯:

我試圖做init().BACKPACK,我現在得到的錯誤:

Traceback (most recent call last): 
    File "game.py", line 94, in <module> 
    welcome_screen() 
    File "game.py", line 85, in welcome_screen 
    gather_gear(player_name) 
    File "C:\Users\thomas_j_perkins\bin\python\game\prepare.py", line 45, in gathe 
r_gear 
    if item in options and item not in init().BACKPACK: # As long as the item i 
s available you can use it 
AttributeError: 'NoneType' object has no attribute 'BACKPACK' 

回答

0

當你做global BACKPACK; BACKPACK = {},你正在創建一個模塊屬性,叫做BACKPACK。要訪問它,請將from settings import init更改爲import settings。這將允許您使用的settings模塊的所有屬性,在你的代碼:

settings.SURVIVAL_TOOLS['meat'] = 1 

你還需要確保settings.init在你的程序中調用一次。您可以打電話的地方在你的代碼,或者更好的是,修改settings.py看起來像這樣:

BACKPACK = {} 
SURVIVAL_TOOLS = {} 

無功能的定義,沒有全局。該代碼將在模塊首次導入到任何地方時運行。下一次是輸入,字典不會被修改。

+0

謝謝,這工作 –