newbee: object's attributes

Duncan Booth duncan at
Mon Aug 12 17:57:15 CEST 2002

Alexander Eisenhuth <stacom at> wrote in
news:3D57D4F8.7090003 at 

> class CTest:
>        ''' filter different link typs, identified by starting sequence
>        '''
>        def __init__ (self):
>            pass
>        def access(self):
>            self._l2.append(1)
>        _l2 = []
> obj = CTest()
> obj.access()
> obj.access()
> newObj = CTest()
> obj.access()
> must I set self._l2 in the constructor to [] that i can speak of a
> object specific attribute ? Is in other words _l2 a attribute of the
> namespace CTest ? 

_l2 in your code is an attribute of the class.

When the class statement is executed, all of the statements in the class 
body are executed in a new namespace (much like a function call). All of 
the local variables created while executing the class body are then used to 
create the class attributes. In your example, the 'local' variables in the 
class body are __init__, access and _l2, so these are stored in the class.

Instance attributes are created when they are assigned through an instance 
such as self. Typically you would do this first in the __init__ method, but 
you may also create instance attributes at any other time.

When you access a method or attribute through an instance, the instance 
attributes are searched first, then the attributes for the class, then the 
attributes for each base class in turn.

New style classes (i.e. subclasses of object) search the base classes in a 
slightly different order from old style classes and may also restrict your 
ability to create new instance attributes.

Duncan Booth                                             duncan at
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