dynamism

Duncan Booth duncan at NOSPAMrcp.co.uk
Tue Sep 10 04:16:12 EDT 2002


steven_shaw at adc.com (Steven Shaw) wrote in
news:66715c02.0209091923.265fe77e at posting.google.com: 

> 
> I thought you could just extend an object's attributes at run-time
> like this: 
> 
>>>> p = object()
>>>> p.x = 1
> Traceback (most recent call last):
>   File "<stdin>", line 1, in ?
> AttributeError: 'object' object has no attribute 'x'

New style classes (which are those with 'object' or other builtin classes 
as a base class) do not all allow you to add arbitrary attributes:

If you have an object which is a builtin type (object, int, dict, ...) then 
you cannot add attributes. If you have an object which is a subclass of a 
builtin type, then you can add attributes unless the subclass defined a 
member __slots__.

The __slots__ attribute in a class, if defined, lists all of the attribute 
names settable in instances of that class. If no __slots__ attribute is 
directly defined in a class then you may add arbitrary attributes (this 
applies even if __slots__ is set in a base class).

An object of a builtin type, or with __slots__ defined in the class and 
all base classes does not have a __dict__ attribute. 

-- 
Duncan Booth                                             duncan at rcp.co.uk
int month(char *p){return(124864/((p[0]+p[1]-p[2]&0x1f)+1)%12)["\5\x8\3"
"\6\7\xb\1\x9\xa\2\0\4"];} // Who said my code was obscure?



More information about the Python-list mailing list