Do I always have to write "self." ?
Martijn Faassen
m.faassen at vet.uu.nl
Fri Apr 28 14:36:04 EDT 2000
Laurent POINTAL <pointal at lure.u-psud.fr> wrote:
> *** Note: taking references copies of the self members is the same
> problem as importing * from a module: its only reference copying...
It's not a problem, Python *always* copies references unless you explicitly
tell it to make a real value copy. I've found it actually quite rare that I
needed a copy by value in my code. This is also why C and C++ code uses
pointers all over the place. C was designed originally with the
idea that copy by value is the most important thing. It's not (though more
important in C than in Python, as integers and such aren't objects). Now
they're stuck with a zillion pointers to structures and objects.
[snip hack]
> But this is still only a reference copying... if you wants to change
> of referenced object in a member, you must use self.xxxxxx.
If the referenced object is mutable, you only need self.xxxx once,
in the beginning of the method, as I demonstrated. You can continue on
with the local variable from then on. Except when you're programming an
object that needs to be persistent in the Zope Object Database; you have
to treat all objects as immutable to make the persistence machinery pick
up your changes and store them. That is, instead of:
# Python
def mymethod(self, foo):
self.mylist.append(foo)
or
def mymethod(self, foo):
mylist = self.mylist
mylist.append(foo)
You have to do something like:
# Python code for ZODB
def mymethod(self, foo):
mylist = self.mylist
mylist.append(foo)
self.mylist = mylist
or
def mymethod(self, foo):
self.mylist.append(foo)
self.mylist = self.mylist
Ugly, but it works.
Regards,
Martijn
--
History of the 20th Century: WW1, WW2, WW3?
No, WWW -- Could we be going in the right direction?
More information about the Python-list
mailing list