简体   繁体   English

我不知道如何使__slots__工作

[英]I don't know how to make __slots__ work

How come this code runs for me? 为什么这个代码会为我运行?

class Foo():
    __slots__ = []
    def __init__(self):
        self.should_not_work = "or does it?"
        print "This code does not run,",self.should_not_work

Foo()

I thought slots worked as a restriction. 我认为插槽是一种限制。 I'm running Python 2.6.6. 我正在运行Python 2.6.6。

__slots__ provides a small optimisation of memory use because it can prevent a __dict__ being allocated to store the instance's attributes. __slots__提供了一个小的内存使用优化,因为它可以防止__dict__被分配来存储实例的属性。 This may be useful if you have a very large number of instances. 如果您有大量实例,这可能很有用。

The restriction you are talking about is mostly an accidental side effect of the way it is implemented. 你所谈论的限制主要是它实施方式的偶然副作用。 In particular it only stops creation of a __dict__ if your class inherits from a base class that does not have a __dict__ (such as object ) and even then it won't stop __dict__ being allocated in any subclasses unless they also define __slots__ . 特别是它只停止创建一个__dict__如果你的类继承自没有__dict__的基类(比如object ),即使那样它也不会停止在任何子类中分配__dict__ ,除非它们也定义__slots__ It isn't intended as a security mechanism, so it is best not to try to use it as such. 它不是一种安全机制,因此最好不要尝试使用它。

All old-style classes get __dict__ automatically, so __slots__ has no effect. 所有旧式类都会自动获取__dict__ ,因此__slots__无效。 If you inherit from object you will get the effect you are looking for, but basically don't bother with __slots__ until you know you have millions of instances and memory is an issue. 如果你从object继承,你将获得你正在寻找的效果,但基本上不要打扰__slots__直到你知道你有数百万个实例和内存是一个问题。

The __slots__ mechanism works for new-style classes. __slots__机制适用于新式类。 You should inherit from object . 你应该继承自object

Change the class declaration to 将类声明更改为

class Foo(object):
  # etc...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM