Reputation: 24804
I have problem updating attributes in a python class, I give a small example.
#!/usr/bin/python
# -*- coding: utf-8 -*-
class myClass():
def __init__(self):
self.s=0
self.procedure()
def procedure(self):#{{{
s=self.s
print s
self.operation()
print s
def operation(self):#{{{
s=self.s
s+=1
self.s=s
print "o:",self.s
c=myClass()
then output
0
o: 1
0
why the last number is 0 and not 1 ?
Upvotes: 1
Views: 291
Reputation: 61643
Because s = self.s
doesn't make s
another name for "whatever you get by checking self.s
, always and forever"; it makes s
another name for "whatever self.s
currently refers to".
The integer 0
is an object. In the first function, you cause self.s
and s
to both refer to that object, and then cause self.s
to refer to something else (the result of the addition) via another s
that's local to the other function. The s
local to the first function is unchanged.
Upvotes: 1
Reputation: 7333
Your procedure
code should read:
def procedure(self):#{{{
s=self.s
print s
self.operation()
# the following line is edited
print self.s
Otherwise, the variable you change (self.s
) doesn't print.
Upvotes: 1
Reputation: 34364
in myClass.procedure()
, you create the local name s
with a value copied from self.s
, which is 0
. In myClass.operation()
, you set self.s
to 1
. But you haven't overwritten your previous copy to s
in myClass.procedure()
, so it is still 0
.
Upvotes: 2