我在python中创建一个非常简单的容器对象,其中一个函数需要创建一个临时的null占位符类,除了告诉程序要删除什么外,什么都不做。
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))
一切似乎都很好(虽然有点乱,但这不重要)但是在运行程序并隐式调用 delitem 方法时,我得到了这个错误:
NameError: global name '_Cycle__cyclepass' is not defined
创建_Cycle__cyclepass
对象时,究竟是什么导致它查找__cyclepass
?