简体   繁体   中英

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.

__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...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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