0

我正在尝试在类 findDist() 中分配变量,但是一旦分配了它们并移动到 closeDist() 上,它就会说未分配变量。

这是错误:"NameError: global name 'Dist1' is not defined"

这是代码,有什么解决办法吗?

n=int(0)
Pro1='alive'
Pro2='alive'
Pro3='alive'
Pro4='alive'
Pro5='alive'
Pro6='alive'
xYou = 1
yYou = 1
xPro1 = 3
yPro1 = 0
xPro2 = 2
yPro2 = 3
xPro3 = 1
yPro3 = 6
xPro4 = 5
yPro4 = 6
xPro5 = 6
yPro5 = 2
xPro6 = 8
yPro6 = 5
proDists = []

def findDist():
    if Pro1 == 'alive':
        Dist1 = (abs(xYou-xPro1)+abs(yYou-yPro1))
        print(Dist1)
    if Pro2 == 'alive':
        Dist2 = (abs(xYou-xPro2)+abs(yYou-yPro2))
        print(Dist2)
    if Pro3 == 'alive':
        Dist3 = (abs(xYou-xPro3)+abs(yYou-yPro3))
        print(Dist3)
    if Pro4 == 'alive':
        Dist4 = (abs(xYou-xPro4)+abs(yYou-yPro4))
        print(Dist4)
    if Pro5 == 'alive':
        Dist5 = (abs(xYou-xPro5)+abs(yYou-yPro5))
        print(Dist5)
    if Pro6 == 'alive':
        Dist6 = (abs(xYou-xPro6)+abs(yYou-yPro6))
        print(Dist6)
    findClose()

def findClose():
    proDists.extend((Dist1,Dist2,Dist3,Dist4,Dist5,Dist6))
    print ("".join(proDists))

findDist()
4

2 回答 2

4

您需要将局部变量作为参数从调用函数发送:

def findDist():

    if Pro1 == 'alive':
        Dist1 = (abs(xYou-xPro1)+abs(yYou-yPro1))
        print(Dist1)
    if Pro2 == 'alive':
        Dist2 = (abs(xYou-xPro2)+abs(yYou-yPro2))
        print(Dist2)
    if Pro3 == 'alive':
        Dist3 = (abs(xYou-xPro3)+abs(yYou-yPro3))
        print(Dist3)
    if Pro4 == 'alive':
        Dist4 = (abs(xYou-xPro4)+abs(yYou-yPro4))
        print(Dist4)
    if Pro5 == 'alive':
        Dist5 = (abs(xYou-xPro5)+abs(yYou-yPro5))
        print(Dist5)
    if Pro6 == 'alive':
        Dist6 = (abs(xYou-xPro6)+abs(yYou-yPro6))
        print(Dist6)
    findClose(Dist1, Dist2, Dist3, Dist4, Dist5, Dist6)

def findClose(Dist1, Dist2, Dist3, Dist4, Dist5, Dist6):

    proDists.extend((Dist1,Dist2,Dist3,Dist4,Dist5,Dist6))
    print ("".join(proDists))
于 2013-10-21T16:06:53.567 回答
0

您可以使用global语句轻松实现它..

def findDist():
    global Dist1, Dist2, Dist3, Dist4, Dist5, Dist6

但是,鼓励避免使用过多的全局变量。findClose()正如 karthikr 所建议的,您可以将它们作为参数传递给:

findClose(Dist1, Dist2, Dist3, Dist4, Dist5, Dist6)

和:

def findClose(Dist1, Dist2, Dist3, Dist4, Dist5, Dist6):

希望这可以帮助!

于 2013-10-21T16:11:06.013 回答