[Tutor] Change to Class-level Variable
Alan Gauld
alan.gauld at btinternet.com
Mon Oct 4 01:58:18 CEST 2010
"Robert" <webtourist at gmail.com> wrote
>>>> class Foo( object ):
> ... myid = 'Foo'
> ... def __init__( self ):
> ... pass
> ...
>>>> f1 = Foo()
>>>> f2 = Foo()
>>>> f1.myid = 'Bar'
This creates a myid instance variable in f1 which hides the class
variable.
You should always modify class variables via the class not an instance
(you can read them either way but I prefer to use the class for both
read
and write)
>>>> Foo.myid = 'SPAM'
>>>> f1.myid <----------------------- Why is "f1" not affected
>>>> by the Class variable change ?
> 'Bar'
Because this is accessing the instance variable not the class one.
You can get at the class variable from the instance usind __class__
but usually you don'tneed to. You know the class in context or you
want the instance data not the class data.
>>> f1.__class__.myid
'SPAM'
HTH,
--
Alan Gauld
Author of the Learn to Program web site
http://www.alan-g.me.uk/
More information about the Tutor
mailing list