Global variables within classes.

Marc 'BlackJack' Rintsch bj_666 at gmx.net
Sat Nov 10 17:15:15 CET 2007


On Sat, 10 Nov 2007 17:00:13 +0200, Donn Ingle wrote:

>> The first creates an attribute of the class, the second creates an
>> attribute in the instance.
> 
> Given that, can you clarify this:
> 
> 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`.

> 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`.

>> Actually the lookup is somewhat more complex than that when you use new-
>> style classes (and you should always use new-style classes): properties
>> (or other objects with a 'get' method) are class attributes but take
>> precedence over instance attributes.
> What is a 'get' method? Do you mean it should get all Java-esque with
> getBlah and setBlah for every little thing?

Good $GOD no!  He's talking about the `__get__` method on properties. Read
the docs for the built in `property()` function.  It's a nice mechanism to
actually avoid all those getters and setters because you can turn "simple"
attributes into "computed" attributes without changing the API of the
objects.

Ciao,
	Marc 'BlackJack' Rintsch



More information about the Python-list mailing list