如何在Python中正确使用私有函数?

2024-10-04 03:18:38 发布

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

我是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}$

我该怎么解决这个问题?在


Tags: 代码inselfforindexreturndef错误
2条回答

您在代码的几个部分中混淆了self.matrixself._matrix和{}。很可能,您的意思是self.matrix或{},其他的都是打字错误。另外,fmatrixSort应该在self上调用__loadVec和{},而不是它当前所做的。在

附加说明:

如果没有要返回的值,则不需要在函数的末尾return。当执行到达函数末尾时,函数将自动返回。在

range可以通过三种方式调用:

range(stop)
range(start, stop)
range(start, stop, step)

如果要从0开始范围,只需省去start参数,用1参数调用range。在

Python没有private函数的概念。但是,它确实处理了名称以至少两个下标线开始、最多以一个下标线结尾的类属性,它会对名称进行处理,使它们更难访问。在这个例子中,您可以看到函数__func2的名称被弄错了。仍然可以访问和调用函数-但是您必须做出特别的努力来执行此操作,只需调用o.func2()失败:

james@bodacious:tmp$cat test.py

class myclass:

    def func1(self):
        print "one"

    def __func2(self):
        print "two"

o = myclass()

print dir(o)

o._myclass__func2()
o.func2()
james@bodacious:tmp$python test.py
['__doc__', '__module__', '_myclass__func2', 'func1']
two
Traceback (most recent call last):
  File "test.py", line 15, in <module>
    o.func2()
AttributeError: myclass instance has no attribute 'func2'
james@bodacious:tmp$

为了回答你的问题:

How do you correctly use private functions in Python?

答案是:就像任何其他函数一样,但是你必须知道这个错误的名称。在

接下来是你想问的问题:

^{pr2}$

来自154号线:

self._matrix.__loadVec(vec,res)

错误消息告诉您,名为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()。因为这是对同一个类中的函数的调用,所以您甚至不必担心名称的损坏-这些函数是要在类中使用的,解释器将为您处理这些损坏。在

james@bodacious:tmp$cat test.py

class myclass:

    def func1(self):
        print "one"

    def __func2(self):
        print "two"

    def func3(self):
        self.__func2()
        print "three"

o = myclass()
print dir(o)
o.func3()
james@bodacious:tmp$python test.py
['__doc__', '__module__', '_myclass__func2', 'func1', 'func3']
two
three

相关问题 更多 >