全局变量给出错误

时间:2013-06-01 11:06:43

标签: python python-2.7

g=0
def smooth(self, a, b):
    k=0
    c = self.name[a]
    d = self.name[b]
    e,f=c,d
    while(e.get_p()!=f.get_p() and e.get_p()!=None and f.get_p()!=None):
        k+=1
        e=e.get_p()
        f=f.get_p()
    if(e.get_p==None and f.get_p()!=None):
        global g
        g+=1
        d=d.get_p()
        return self.smooth(a,d.name)
    return(k,g)

忽略调用的函数,但是在if语句中它没有更新g的值并且在使用值调用时出现错误全局名称'g'未定义。请帮助

1 个答案:

答案 0 :(得分:3)

在此代码中:

g=0
def smooth(self, a, b):

smooth看起来像一个类实例方法,因此g看起来像一个类变量,而不是全局变量,因此global关键字不起作用。请尝试将其称为MyClass.g(其中“MyClass”是您班级的实际名称)或__class__.g

相关问题