Data attributes...

Emile van Sebille emile at fenx.com
Thu Jan 24 13:46:10 EST 2002


"Lawrence Oluyede" <rhymes at myself.com> wrote in message
news:uth05ukhtcgs7rfkfl7a0724soknb23neo at 4ax.com...
>
> I've just read about data attributes.
>
> The tut says:
>
> "Data attributes need not be declared; like local variables, they
> spring into existence when they are first assigned to"
>
> Why that? I think it could be illegal...
>

You can have the class enforce rules that only allow pre-defined
attributes.  Look for __setattr__ as you continue through the tutorial.
Here's a quick example:

C:\>python
ActivePython 2.1, build 210 ActiveState)
based on Python 2.1 (#15, Apr 19 2001, 10:28:27) [MSC 32 bit (Intel)] on
win32
Type "help", "copyright", "credits" or "license" for more information.
>>> class Test:
...     allowed = ('a','b','c')
...     def __setattr__(self,var,val):
...             if var in Test.allowed:
...                     self.__dict__[var] = val
...             else:
...                     raise AttributeError
...
>>> t = Test()
>>> t.a = 1
>>> t.d = 3
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
  File "<stdin>", line 7, in __setattr__
AttributeError
>>> t.a
1
>>>

HTH,


<I thought there was an activestate cookbook entry illustarting this,
but I couldn't spot it... pointers?>


--

Emile van Sebille
emile at fenx.com

---------




More information about the Python-list mailing list