I just make a foo class to explain what I mean:
class Foo:
def __init__(self, fakevalue):
self.fv = fakevalue
@staticmethod
def make_a_foo():
return Foo(2)
def try_change_foo_value(self):
self = Foo.make_a_foo()
print "in change function, self.fv:", self.fv
if(__name__ =='__main__'):
foo_instance = Foo(1)
print "foo_instance.fv:", foo_instance.fv
foo_instance.try_change_foo_value()
print "foo_instance.fv:", foo_instance.fv
I expect:
foo_instance.fv: 1
in change function, self.fv: 2
foo_instance.fv: 2
But the result is:
foo_instance.fv: 1
in change function, self.fv: 2
foo_instance.fv: 1
We can see the self value has already changed, but the instance value does not.
Why? And how to solve this problem?
In this case,
selfis a pointer to the caller instance. Though you change the pointer intry_change_foo_value, it is just like changing a parameter in a function: it has no effect outside the method.To clarify this, you can consider
a.try_change_foo_value()as shorthand forFoo.try_change_foo_value(a). This should make it obvious that when you changeself, you are changing a local variable, whilea, the caller, remains unchanged.To fix it, you should do
but as mgilson points out, it is more Pythonic to just say
foo_instance.fv = 2.If you want to actually change the value of
foo_instance(rather than justfv), you should do that elsewhere, not in a method (which makes little conceptual sense).