我在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))

一切看起来都很好(虽然有点混乱,但这不重要),但是在运行程序并隐式调用delitem方法时,我会得到以下错误:
NameError: global name '_Cycle__cyclepass' is not defined

究竟是什么导致它在创建_Cycle__cyclepass对象时查找__cyclepass

最佳答案

[按建议将我的评论移至答案]
这是python的name mangling私有成员的结果。将双下划线前缀重命名为单下划线,问题就解决了。

09-11 19:21
查看更多