Is this a __slot__ bug?
Raymond Hettinger
python at rcn.com
Mon Jul 1 00:40:09 EDT 2002
"Ian McMeans" <imcmeans at home.com> wrote
> I wasn't able to find a good documentation of slots on the python website.
> Do you have a link handy? I guess I'm just bad at searching, I couldn't
find
> a description in the first few pages of google either.
Slots
The __slots__ tool changes the way a class implements instance variables.
Each variable listed is given pre-allocated space in an instance, as opposed
to the standard method of giving each instance its own dictionary.
There are two results of using __slots__. First, the instance loses its
dynamic character and is protected from creating variables not specifically
listed in __slots__. Second, the size of the instance becomes smaller
because a dictionary is not required.
Its use is indicated when an application uses a large number of instances,
storage costs are high due to the number of instances, and the instances do
not require dynamic attribute creation. For example, a Node class for a
binary tree may achieve considerable space savings:
class Node(object):
__slots__ = ['value','left','right']
def __init__(self,value=0):
self.value = value
self.left = self.right = None
def show(self):
if self.left: self.left.show()
print self.value
if self.right: self.right.show()
n = Node('root')
n.left = Node('ginger')
n.right = Node('sounds like')
n.right.right = Node('bang')
n.right.right.right = Node('bong')
n.right.right.left = Node('bing')
n.show()
Raymond Hettinger
More information about the Python-list
mailing list