[英]Calling other scripts and using variables (Python)
我不确定该怎么做...
我想使用import转到另一个脚本(一旦调用,原始脚本已完成),但是我需要第二个脚本来从原始脚本中打印变量。
因此,我可以导入第二个脚本并正常使用打印件,但是,如果尝试导入原始脚本,则可以访问该变量。
但是,如果我这样做,只会给我一个错误:
Traceback (most recent call last):
File "C:\Users\luke\Desktop\k\startGame.py", line 2, in <module>
import Storyline
File "C:\Users\luke\Desktop\k\Storyline.py", line 1, in <module>
import startGame
File "C:\Users\luke\Desktop\k\startGame.py", line 56, in <module>
Storyline.startGame1()
AttributeError: 'module' object has no attribute 'startGame1'
我正在尝试打印此:
print ("I see you have picked " + startGame.currentPokemon)
我这样称呼它:
Storyline.startGame1()
而当前的神奇宝贝是
currentPokemon = inputKK
(InputKK是入门口袋妖怪的输入)
有什么办法吗? 是的,我正在用Python制作口袋妖怪游戏,但这是一个不使用真实口袋妖怪名称的版本。
故事情节脚本:
import startGame
def startGame1():
print ("Welcome to the H.Q of I.O.D")
print ("I am Professor Steel.")
print ("I see you have picked " + startGame.currentPokemon)
startGame脚本:
import Storyline
inputKK = input("Choose from, 'Craigby', 'Robinby' or 'KKby' ")
if(inputKK == "Craigby"):
print("Craigby is a electric type.")
print("Craigby: Attack = 7, Defence = 3, Health = 6, Speed = 12")
if(inputKK == "Robinby"):
print("Robinby is a fire type.")
print("Robinby: Attack = 6, Defence = 5, Health = 7, Speed = 7")
if(inputKK == "KKby"):
print("KKby is a water type.")
print("KKby: Attack = 5, Defence = 8, Health = 11, Speed = 5")
print("")
os.system('cls')
currentPokemon = inputKK
counter = 0;
while(counter < 1):
print("Welcome to pokeby.")
print("Type S for [STORYLINE]")
print("Type R for pokemon in the field [CURRENT IS GRASS] ")
print("Type Q for [QUIT]")
inputMainMenu = input("S/R/Q ...")
if(inputMainMenu == "S"):
os.system('cls')
counter = counter + 2
Storyline.startGame1()
if(inputMainMenu == "R"):
os.system('cls')
counter = counter + 2
if(inputMainMenu == "Q"):
os.system('cls')
inputExit = input("Are you sure you want to quit? Y/N ")
if(inputExit == "Y" or inputExit == "y"):
print("K")
else:
counter = counter + 1
您正在尝试import Storyline
到startGame
,并且还试图import startGame
到Storyline
。 您只是无法进行这种递归导入。 import
startGame
,在定义startGame1()
之前, Storyline
会遇到您的Storyline.startGame1()
调用,因此会出现no attribute错误。
您应该重组您的文件,以便不必要。
不要在您的Storyline
脚本中import StartGame
。 而是将所需的值传递给StartGame1
函数。
# Storyline.py
def startGame1(currentPokemon):
print ("Welcome to the H.Q of I.O.D")
print ("I am Professor Steel.")
print ("I see you have picked ", currentPokemon)
然后在startGame
,调用Storyline.startGame1(inputKK)
并传递口袋妖怪的名称。
顺便说一句,您的startGame1
函数不在模块startGame
,这有点令人困惑...
[ 编辑:不听我说; 已经很晚了,我对自己说的话没有足够的思考。]
您不能在类似的模块中引用属性或方法。 您需要的是将您的方法放在一个类中。 另外, 我认为您可以 from Storyline import startGame1()
。但实际上,请使用类[如果需要]; [我认为]他们很好。 有关类的Python文档。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.