By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
459,200 Members | 1,612 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 459,200 IT Pros & Developers. It's quick & easy.

HELP : class and variables

P: n/a
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 t.var1=6
print t.res 3


??????????????????
I though that everithing is memory zones.
Why it's not 8 ?

Thanks
Jul 18 '05 #1
Share this Question
Share on Google+
2 Replies


P: n/a
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

Jul 18 '05 #2

P: n/a
vincent delft skrev:
Can you explain the following ?
Yes.
class test:
var1=1
var2=2
res=var1+var2 t=test()
print t.res
3
t.var1=6
print t.res 3


Changing var1 does not change res.

You might like to make it a function instead:

class Test:
var1=1
var2=2
def res (self):
return self.var1+self.var2

t=Test()
t.var1=6
print t.res()

I learned in Java to give classes names with the first letter
capitalized. I find that a useful convention.

--
Bertel, Denmark
Jul 18 '05 #3

This discussion thread is closed

Replies have been disabled for this discussion.