Global variables within classes.

Donn Ingle donn.ingle at gmail.com
Sat Nov 10 11:53:08 EST 2007


Included again for clarity:
>> class Test:
>>     attribute = "original value"
>>     
>> class Bob:
>>     def __init__(self):
>>         self.ref = Test()
>>         
>> class Jim:
>>     def __init__(self):
>>         self.ref = Test()
>>         
>> b = Bob()
>> j = Jim()
>> 
>> print b.ref.attribute #prints "original value"
>> b.ref.attribute = "haschanged"
>> ## Where is the value "haschanged" going here?
> 
> To *instance* of `Test` you created and bound to `b.ref`.
> 
I don't follow you here. I *think* you are saying I created a *new* (on the
fly) ref within b that is also called 'attrib', so that it's kind of
shadowing the original 'attribute' ref (the so-called class attribute.)
?

>> print b.ref.attribute # print "haschanged"
>> 
>> print j.ref.attribute #prints "original value"
>> ## If it changed and an attribute of the Class, then
>> ## why is it back to "original value" ?
> 
> Because the *instance* of `Test` bound to `j.ref` does not have
> `attribute` it is looked up in the *class* `Test`.
Okay, I sort of see that. It's not a property of 'j' so it looks upwards
into the class. 
This is kind of weird. It's not clear like Python usually is. Is this
something intentional or did it 'fall through the cracks'? I mean, can one
rely on it or will it be 'fixed'?
 
> Good $GOD no!  
:D

> He's talking about the `__get__` method on properties. Read 
> the docs for the built in `property()` function.  
Okay, I'll go have a look.

Thx
\d





More information about the Python-list mailing list