Posts Tagged ‘Object’

Python: constrain objects attribute list

From Python 2.2 on, it’s possible to constrain the list of attributes that can be referenced on an object using the new __slots__ class attribute. Python objects are usually very dynamic; at any time it’s possible to define a new attribute on an instance by just doing obj.new_attr=1. A new-style class can define a class attribute named __slots__ to limit the legal attributes to a particular set of names. An example will make this clear:

>>> class C(object):
...     __slots__ = ('template', 'name')
>>> obj = C()
>>> print obj.template
>>> obj.template = 'Test'
>>> print obj.template
>>> obj.newattr = None
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
AttributeError: 'C' object has no attribute 'newattr'

Note how you get an AttributeError on the attempt to assign to an attribute not listed in __slots__.

Snipped from Python 2.2 release notes.
See also the __slots__ paragraph in Python langage reference about customizing attributes access.

Catégories :Python Étiquettes : , , , ,
%d blogueurs aiment cette page :