这段代码是怎么运行的?我不知道如何让__slots__工作
class Foo():
__slots__ = []
def __init__(self):
self.should_not_work = "or does it?"
print "This code does not run,",self.should_not_work
Foo()
我想插槽做过限制。我正在运行Python 2.6.6。
这段代码是怎么运行的?我不知道如何让__slots__工作
class Foo():
__slots__ = []
def __init__(self):
self.should_not_work = "or does it?"
print "This code does not run,",self.should_not_work
Foo()
我想插槽做过限制。我正在运行Python 2.6.6。
__slots__
机制适用于新式类。你应该继承object
。
类声明更改为
class Foo(object):
# etc...
__slots__
提供内存使用的小优化,因为它可以防止__dict__
被分配到存储实例的属性。如果您有大量实例,这可能会很有用。
您所谈论的限制大多是其实施方式的意外副作用。特别是,如果您的类继承自没有__dict__
(例如object
)的基类并且即使不会在任何子类中分配__dict__
,也会停止创建__dict__
,除非它们也定义了__slots__
。它并不是作为一种安全机制,所以最好不要尝试像这样使用它。
所有旧式课程自动获得__dict__
,因此__slots__
不起作用。如果你从object
继承,你会得到你正在寻找的效果,但基本上不要打扰__slots__
,直到你知道你有数百万的实例和内存是一个问题。
太棒了!谢谢! – 2011-02-01 09:25:37