私信  •  关注

Cireo

Cireo 最近创建的主题
Cireo 最近回复了
4 年前
回复了 Cireo 创建的主题 » python何时以及为什么忽略插槽?[副本]

你的问题在里面有答案 Usage of __slots__?

Requirements:
To have attributes named in __slots__ to actually be
stored in slots instead of a __dict__, a class must
inherit from object.

To prevent the creation of a __dict__, you must
inherit from object and all classes in the inheritance
must declare __slots__ and none of them can
have a '__dict__' entry.

尤其是,你必须有一个完整的 __slots__ 从最初的 object 继承到当前类,否则您将拥有 __dict__ 可用,插槽将无法阻止修改。

对象不使用槽,所以不能使用它的子类来阻止设置属性

4 年前
回复了 Cireo 创建的主题 » 在追加和迭代新值时循环python列表

您可能需要查看另一个数据结构,比如队列或堆栈。

作为一个非常糟糕的例子,有一些图算法离下面的逻辑不太远:

seen = set()
stack = [1]
while stack:
    current = stack.pop()
    if current in seen or abs(current) > 5:
        continue
    seen.add(current)
    print 'Processed %s' % current
    stack.append(current + 1)
    stack.append(current - 1)

将提供

Processed 1
Processed 0
Processed -1
Processed -2
Processed -3
Processed -4
Processed -5
Processed 2
Processed 3
Processed 4
Processed 5