开发者

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.sho开发者_JAVA百科uld_not_work

Foo()

I thought slots worked as a restriction. I'm running 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. 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__. 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. 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.


The __slots__ mechanism works for new-style classes. You should inherit from object.

Change the class declaration to

class Foo(object):
  # etc...
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜