仅在类中指定的变量

2024-05-16 00:03:36 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图在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()

Tags: ifabsprintalivedist2dist1pro1dist3
2条回答

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

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))

您可以使用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):

希望这有帮助!你知道吗

相关问题 更多 >