Python OO——成员函数定义和关键字 self
我正在用这个构造函数编写一个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_
并定义两个成员函数:
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()
调用第二个函数时,会发生错误:
NameError: global name 'buildSimplex' is not defined
你有线索吗?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
乍一看,我会说这是一个识别问题,但您需要提供实际代码以获得更具体的答案。
我之所以这样说是因为您遇到了错误。如果您正确声明了您的类,并尝试调用未定义的实例的方法,您实际上应该得到一个:
AttributeError:实例没有属性'xxxx'
。如果方法是在类中声明的,则无需关心定义方法的顺序。请参阅下面的met1
和met4
示例例如:
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 ofmet1
andmet4
belowFor example:
您的错误
NameError: global name 'buildTool1' is not Defined
表示您正在尝试访问变量buildTool1
但其未在本地或全局中定义。请检查这个
Your error
NameError: global name 'buildTool1' is not defined
says you are trying to access the variablebuildTool1
buts its not define in local or global.Please check this