Best practice for object attributes?

Robin Munn rmunn at pobox.com
Fri Apr 4 10:15:19 EST 2003


Michael Sparks <michaels at rd.bbc.co.uk> wrote:
> Carl, Jp Calderone, laotseu:
> 
> Thanks for the comments between the 3 of you I now understand the
> behaviour of the following ....
> 
>> python2.3
> Python 2.3a2 (#1, Feb 20 2003, 09:54:48)
> [GCC 3.2] on linux2
> Type "help", "copyright", "credits" or "license" for more information.
>>1> class A: time='today'
> ...
>>2> B=A()
>>3> B_CB=A()
>>4> B.time='yesterday'
>>5> A.time='tomorrow'
>>6> C=A()
>>7> C.time
> 'tomorrow'          #1#
>>8> B.time
> 'yesterday'         #2#
>>9> B_CB.time
> 'tomorrow'          #3#
> 
> ... to be this ....
> 
> 1 Creates a class with class attribute "time", value 'today'.
> 2 Creates an object "B" with an empty __dict__, no local attributes
> 3 Creates an object "B_CB" with an empty __dict__, no local attributes
> 4 Inserts into "B" a local attribute "time" with value 'tomorrow'
> 5 Changes the class attribute "time" to 'tomorrow'
> 6 Creates an object "C" with an empty __dict__, no local attributes
> 
> 7 The system looks in C for a local attribute time, and does not find
>   one. It then looks in the class to see if it has attribute time, finds
>   one and treats *that* as the value of C.time. 
>   Hence the system gets the value of A.time - specifically 'tomorrow'
>   hence the output on line #1#
> 
> 8 The system looks in B for a local attribute time - it finds one with
>   the value 'yesterday' in B's dict, hence the output on line #2#
> 
> 9 The system looks in B_CB for a local attribute time, and does not find
>   one. It then looks in the class to see if it has attribute time, finds
>   one and treats *that* as the value of B_CB.time. 
>   Hence the system gets the value of A.time - specifically 'tomorrow'
>   hence the output on line #3#

Exactly right.

By the way, having just picked up a copy of _Python in a Nutshell_ by
Alex Martelli, I highly recommend it. Run, don't walk, to your nearest
bookstore and buy yourself a copy. (Or do what I do and order from
Bookpool.com and get about 40% off O'Reilly titles!) Pages 75-76 of
_Python in a Nutshell_ have an excellent discussion of this very
subject.

-- 
Robin Munn <rmunn at pobox.com>
http://www.rmunn.com/
PGP key ID: 0x6AFB6838    50FF 2478 CFFB 081A 8338  54F7 845D ACFD 6AFB 6838




More information about the Python-list mailing list