HELP : class and variables

V

vincent delft

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.rest.var1=6
print t.res
??????????????????
I though that everithing is memory zones.
Why it's not 8 ?

Thanks
 
B

Bruno Desthuilliers

vincent said:
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

Until here, t.var1 means test.var1 (class variable)

From here, you created a new instance variable for object t, named
var1. It hides test.var1.
print t.res

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 :.... def __init__(self):
.... # create instance variables
.... self.var1 = 1
.... self.var2 = 2
.... def res(self):
.... return self.var1 + self.var2
....8

Bruno
 
B

Bertel Lund Hansen

vincent delft skrev:
Can you explain the following ?
Yes.

class test:
var1=1
var2=2
res=var1+var2
t=test()
print t.res
t.var1=6
print t.res

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.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,009
Latest member
GidgetGamb

Latest Threads

Top