使用插槽有缺点吗?

2024-09-29 17:14:03 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在使用python3.7和Django。我在读关于“吃角子老虎机”的书。显然,通过这样做,\ U插槽可以用来优化大量这些对象的内存分配。。。你知道吗

class MyClass(object):
    __slots__ = ['name', 'identifier']
    def __init__(self, name, identifier):
        self.name = name
        self.identifier = identifier
        self.set_up()

我最明显的问题是,为什么我们不想对所有对象都这样做呢?使用插槽有缺点吗?你知道吗


Tags: 对象django内存nameselfobjectinitdef
1条回答
网友
1楼 · 发布于 2024-09-29 17:14:03

Fluent PythonbyLuciano Ramalho列出了以下注意事项

• You must remember to redeclare __slots__ in each subclass, since the inherited attribute is ignored by the interpreter.

• Instances will only be able to have the attributes listed in __slots__, unless you include __dict__ in __slots__ — but doing so may negate the memory savings.

• Instances cannot be targets of weak references unless you remember to include __weakref__ in __slots__.

相关问题 更多 >

    热门问题