Python OO成员函数定义和关键字s

2024-10-01 05:00:44 发布

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

我用这个构造函数编写一个Python类:

      #constuctor
def __init__(self, initPt_=[1,1],fun_=Optim_tests.peaks,NITER_=30,alpha_=0.7,NMAX_=5000,FTOL_=10**(-10)):
    self.initPt = initPt_
    self.fun = fun_
    self.alpha = alpha_
    self.ITER = NITER_
    self.NMAX = NMAX_
    self.FTOL = FTOL_

以及定义两个成员函数:

^{pr2}$

调用第二个函数时,发生错误:

NameError: global name 'buildSimplex' is not defined    

你有线索吗?在


Tags: 函数selfalphainitdeftestsoptimfun
2条回答

乍一看,我会说这是一个识别问题,但是你需要提供一个更具体的答案的实际代码。在

我之所以这么说是因为你犯了错误。如果正确地声明了类,并尝试调用未定义实例的方法,那么实际上应该得到一个:AttributeError: A instance has no attribute 'xxxx'。如果方法在类中声明,则不需要关心定义方法的顺序。请参见下面的met1met4的示例

例如:

class A():
   def met1(self):
      print self.met4()

   def met2(self):
      self.met3()

   def met4():
      print 'x'


 a = A()
 a.met1()
 >>> x
 a.met2()
 >>> AttributeError: A instance has no attribute 'met3'

您的错误NameError: global name 'buildTool1' is not defined表示您试图访问变量buildTool1,但它没有在本地或全局中定义。在

请检查一下这个

class test(object):

    def __init__(self, name):
        self.name = name

    def buildSimplex(self):
        print "CALL"

    def sA(self):
        self.buildSimplex()


if __name__ == '__main__':
    x = test('test')
    x.sA()

相关问题 更多 >