cpbotha.net

voices in my head

cpbotha.net random header image

Python new-style objects and __slots__

June 16th, 2003 · No Comments · Uncategorized

This should be very useful:

In [5]: class oldObject:
...: ....def __init__(self):
...: ........self.someVar = 1
...:
In [6]: o1 = oldObject()
In [7]: o1.someVar = 2
In [8]: o1.someOtherVar = 3

This is of course expected behaviour. Have a look at this though:

In [9]: class newObject(object):
...: ....__slots__ = ['someVar']
...: ....def __init__(self):
...: ........self.someVar = 1
...:
In [10]: o2 = newObject()
In [11]: o2.someVar = 2
In [12]: o2.someOtherVar = 3
AttributeError: 'newObject' object has no attribute 'someOtherVar'

Neat huh? In short, deriving from the new Python class ‘object’ means you have a “new-style” object. Amongs other things, this means that you can define a __slots__ list which will prevent the use of attributes not in that list. These objects are available from Python 2.2 onwards.

No, my books haven’t arrived yet. :)

Related posts:

  1. Python new-style object method resolution order
  2. Interesting Python factoid of the week
  3. Adding ErrorEvent handlers to all VTK objects in Python
  4. Python IDE wanted, good, cheap and fast. :)
  5. IronPython video demonstration by Jim Hugunin

Tags:

No Comments so far ↓

There are no comments yet...Kick things off by filling out the form below.

Leave a Comment