3

Possible Duplicate:
Can set any property of Python object

In [67]: obj = object()    
In [68]: obj.x = 42
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
/home/user/<ipython-input-68-0203a27904ca> in <module>()
----> 1 obj.x = 42

AttributeError: 'object' object has no attribute 'x'    
In [69]: class myc(object):
   ....:     pass
   ....:     
In [70]: my = myc()    
In [71]: my.x = 42

Looks like an inconsistency. How do I make my classes similar to object without allowing to add new attributes?

Community
  • 1
  • 1
balki
  • 26,394
  • 30
  • 105
  • 151

1 Answers1

2

Most builtin types do not allow custom attributes, as these come with the overhead of a dictionary associated to each instance. Custom classes have such a dictionary by default (it's accessible via the __dict__ attribute), but you can avoid its creation by adding

__slots__ = []

to the class definition – see the documentation for full details.

Sven Marnach
  • 574,206
  • 118
  • 941
  • 841