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

2024-03-28 22:09:04 发布

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

假设下面的类显示某种层次结构:

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]

通过访问其他的超对象的隐藏属性来设置它,这真的是最好的方法吗?该属性不应由用户设置。。你知道吗


Tags: selffalsetrueindexlenreturnif属性
1条回答
网友
1楼 · 发布于 2024-03-28 22:09:04

_foo只是一种命名约定。通常,会有一个属性或其他东西为您设置“private”变量。如果没有,公约正在(轻微地)被滥用。你知道吗

相关问题 更多 >