Python OO — member function definition and keyword self
-
29-10-2019 - |
Question
I am writting a Python class with this constructor:
#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_
and defining both member functions:
def buildSimplex(self):
self.simplex=[]
self.simplex.append([x for x in self.initPt])
for i in range(len(self.initPt)):
temp=[x for x in self.initPt]
temp[i]=self.initPt[i]+1
self.simplex.append(temp)
self.npts=len(self.simplex)
def sA(self):
self.buildSimplex()
When calling second functions, error happens:
NameError: global name 'buildSimplex' is not defined
Do you have a clue?
Solution
At first sight I would say it's a identation problem, but you need to provide the actual code for a more specific answer.
The reason I'm saying this is because of the error you're getting. If you declared your class properly, and try to call a method of an instance that is not define, you should actually get a: AttributeError: A instance has no attribute 'xxxx'
. And you don't need to care about the order you define your methods if they are declared in a class. See the e xample of met1
and met4
below
For example:
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'
OTHER TIPS
Your error NameError: global name 'buildTool1' is not defined
says you are trying to access the variable buildTool1
buts its not define in local or global.
Please check this
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()