访问“私有”的最Pythonic方式是来自另一个类实例的变量
想象一下以下显示某种层次结构的类:
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]
通过访问其隐藏属性来设置 other 的超级对象真的是最好的(或唯一)方法吗?该属性不应由用户设置..
Imagine the following class that displays some sort of hierarchy:
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]
Is it really the best (or the only) way to set the superobject of other by accessing it's hidden attribute ? The attribute should not be set by the user ..
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
_foo
只是一个命名约定。通常,会有一个属性或其他东西为您设置“私有”变量。如果不是,那么该约定就被(轻微)滥用了。_foo
is just a naming convention. Usually, there would be a property or something that sets the 'private' variable for you. If not, the convention is being (slightly) misused.