从另一个类实例访问“私有”变量的最pythonic方式

时间:2011-08-03 10:29:05

标签: python private-members

想象一下以下显示某种层次结构的类:

class BaseList2D(object):
    def __init__(self):
        self._superobject   = None
        self._subobjects    = []

    def InsertUnder(self, other):
        if self not in other._subobjects:
            other._subobjects.append(self)
            self._superobject   = other
            return True
        return False

    def InsertAfter(self, other):
        parent  = other._superobject
        if not parent:
            return False

        parent  = parent._subobjects
        parent.insert(parent.index(other) + 1, self)
        return True

    def GetDown(self):
        if not len(self._subobjects):
            return
        return self._subobjects[0]

    def GetNext(self):
        if not self._superobject:
            return
        stree   = self._superobject._subobjects
        index   = stree.index(self)
        if index + 1 >= len(stree):
            return
        return stree[index + 1]

通过访问隐藏属性来设置其他的超级项目真的是最好的(或唯一的)方法吗?该属性不应由用户设置..

1 个答案:

答案 0 :(得分:1)

_foo只是一个命名约定。通常,会有一个属性或某些东西为您设置'private'变量。如果没有,该公约正在(轻微)滥用。

相关问题