HELP : class and variables
Bruno Desthuilliers
bdesth.nospam at removeme.free.fr
Mon Sep 1 12:34:26 EDT 2003
vincent delft wrote:
> Sorry if my question is stupid.
> I've missed something with classes.
> Can you explain the following ?
> class test:
> var1=1
> var2=2
> res=var1+var2
>
> t=test()
> print t.res
>
>>>3
Until here, t.var1 means test.var1 (class variable)
> t.var1=6
From here, you created a new instance variable for object t, named
var1. It hides test.var1.
> print t.res
>
>>>3
What would you expect ?
1/ assigning to t.var1 does not modify test.var1
2/ modifiying test.var1 would not modify test.res anyway ! Guess why ?
Try this instead :
>>> class test:
... def __init__(self):
... # create instance variables
... self.var1 = 1
... self.var2 = 2
... def res(self):
... return self.var1 + self.var2
...
>>> t = test()
>>> t.res()
3
>>> t.var1 = 6
>>> t.res()
8
Bruno
More information about the Python-list
mailing list