我是Python新手,当涉及到私有函数时,我面临一些问题。我想在一个公共方法中调用其中两个,只是为了让代码看起来更清晰,但是我根本无法理解运行时错误显示了什么。以下是完整代码中有问题的部分:
def __loadVec(self,vec,res):
for i in range(0,res.getRows()):
for j in range(0,res.getColumns()):
vec.append(self.matrix[i][j])
return
def __savetoMatrix(self,vec,res):
index = 0
for i in range(0,res.getRows()):
for j in range(0,res.getColumns()):
self.matrix[i][j] = vec[index]
index += 1
return
def fmatrixSort(self,res):
try:
print "Sorting matrix information..."
vec = []
self._matrix.__loadVec(vec,res)
vec.sort()
self_matrix.__savetoMatrix(vec,res)
except TypeError:
print "TypeError in fmatrixSort"
return
我要做的是完全组织一个矩阵,这样它从最小值开始,到最高值结束。在
这是程序显示的错误:
^{pr2}$我该怎么解决这个问题?在
您在代码的几个部分中混淆了}。很可能,您的意思是},其他的都是打字错误。另外,},而不是它当前所做的。在
self.matrix
、self._matrix
和{self.matrix
或{fmatrixSort
应该在self
上调用__loadVec
和{附加说明:
如果没有要返回的值,则不需要在函数的末尾
return
。当执行到达函数末尾时,函数将自动返回。在range
可以通过三种方式调用:如果要从0开始范围,只需省去
start
参数,用1参数调用range
。在Python没有
private
函数的概念。但是,它确实处理了名称以至少两个下标线开始、最多以一个下标线结尾的类属性,它会对名称进行处理,使它们更难访问。在这个例子中,您可以看到函数__func2
的名称被弄错了。仍然可以访问和调用函数-但是您必须做出特别的努力来执行此操作,只需调用o.func2()
失败:为了回答你的问题:
答案是:就像任何其他函数一样,但是你必须知道这个错误的名称。在
接下来是你想问的问题:
^{pr2}$来自154号线:
错误消息告诉您,名为
self
的对象是matrix
类的实例;但它没有名为_matrix
的属性。参考上面的__savetoMatrix
函数,看起来该属性只是名为matrix
-因此需要将其称为self.matrix
(“名为self
的对象的matrix
的属性)。在此}。在
__savetoMatrix
函数引用self.matrix
,而不是{然而,这里还有一个更深层次的问题。从行与行之间看,这段代码似乎来自一个名为
matrix
的类;该类的实例有一个名为matrix
的属性。当您调用self.matrix.__loadVec()
时,您正在调用名为__loadvec()
的函数,该函数绑定到绑定到名为self
的对象的属性matrix
。在即使这是您想要做的,这也无法工作,因为上面概述的名称混乱-假设名为
matrix
的属性具有类inner_matrix
,那么您必须将函数称为self._matrix._inner_matrix__loadVec()
我认为您实际要做的是调用在类
matrix
中定义的__loadVec()
方法。为此,只需调用self.__loadVec()
。因为这是对同一个类中的函数的调用,所以您甚至不必担心名称的损坏-这些函数是要在类中使用的,解释器将为您处理这些损坏。在相关问题 更多 >
编程相关推荐