我是python的新手,所以我很抱歉这是一个简单的问题,我正在创建一个程序,我需要在多个文件中共享一个全局变量。我有一个名为settings.py
的文件,如下所示:
def init():
global BACKPACK
global SURVIVAL_TOOLS
BACKPACK = {}
SURVIVAL_TOOLS = {}
我import
将这些设置放入另一个名为battle.py
和prepare.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 :(得分:0)
执行global BACKPACK; BACKPACK = {}
时,您正在创建名为BACKPACK
的模块属性。要访问它,请将from settings import init
更改为import settings
。这将允许您在代码中使用settings
的所有模块属性:
settings.SURVIVAL_TOOLS['meat'] = 1
您还需要确保在程序中调用settings.init
一次。您可以在代码中的某个位置调用它,或者更好的是,将settings.py
修改为如下所示:
BACKPACK = {}
SURVIVAL_TOOLS = {}
没有函数定义,没有全局变量。第一次将模块导入任何地方时,此代码将运行。下次导入时,不会修改dicts。