Python 在另一个对象中创建对象实例时出错
-
26-12-2019 - |
题
我正在 python 中创建一个非常简单的容器对象,它的函数之一需要创建一个临时的空占位符类,该类除了告诉程序要删除什么之外什么都不做。
class __cyclepass(object):
"Null class as a placeholder for deleting items in a cycle."""
pass
class Cycle(object):
def __init__(self, *args):
self.l = list(args)
#.........................
def __delitem__(self, key):
"""Magic method for deleting items via indexing."""
try:
if isinstance(key, slice):
s = key.start; e = key.stop; stp = key.step if key.step else 1
slicelen = abs((s - e) // stp)
if slicelen == 1:
steps = [s]
else:
steps = [s + stp * i for i in range(slicelen)]
_list = copy(self.l)
for step in steps:
index = step % len(self)
_list[index] = __cyclepass() #this is where an error occurs
self.l = list(filter(lambda x: x.__class__ != __cyclepass, _list))
else:
index = key % len(self)
del self.l[index]
except:
raise IndexError("Bad index %s" % str(key))
一切看起来都很好(虽然有点乱,但这不是重点),但是在运行程序并隐式调用 删除 方法我得到这个错误:
NameError: global name '_Cycle__cyclepass' is not defined
到底是什么导致它寻找 _Cycle__cyclepass
创建时 __cyclepass
目的?
解决方案
[按照建议将我的评论移至答案]
这是python的结果 名称修改 “私人”成员。从双下划线前缀重命名为单下划线,问题就解决了。
不隶属于 StackOverflow