Overloading the = operator?
Hamish Lawson
hamish_lawson at yahoo.co.uk
Sun Apr 23 12:50:27 EDT 2000
Jerome
There seem to be two issues here: copying the contents of one
object to another and adding two objects together. I'll use a
cut-down version of your example.
class Base:
def __init__(self, q):
self.list = q
def __add__(self,other):
return self.list + other.list
x = Base([1,2])
y = Base([2,4,3])
z = Base([])
z = x + y
I'm guessing that your coming at this from a C++ viewpoint, so
I'll try to relate the discussion to C++ concepts.
Let's deal with copying objects first. Whereas in C++ assignment
is a copying operation, you have learnt by now that in Python it
is a name binding operation. Thus the statement z = x doesn't
copy the contents of x over to z, but instead makes the name z
be another reference to the object that x refers to. If we want
z to have the same value as x but be an independent object, then
we first need to make a new object that is a clone of x and then
assign z to this new object. We can clone objects using the copy
module; we'll also define a __copy__() method for the Base class:
class Base:
def __init__(self, q):
self.list = q
def __add__(self,other):
return self.list + other.list
def __copy__(self):
copiedlist = self.list[:] # make a copy of the list
return Base(copiedlist)
import copy
x = Base([1,2])
z = copy.copy(x) # calls x.__copy__()
In Python as in C++ the question of shallow and deep copying
crops up. Our __copy__() method has been defined so that the
cloned object gets its own copy of the list attribute (see the
copy module for a discussion of shallow and deep copying).
However you may not need to bother with copying if your real
concern is with adding objects together, which we'll now
consider. The __add__() method as currently defined returns a
list, but it should really return a new Base object (this is in
fact what an overloaded operator+ would be expected to do in C++
too).
class Base:
def __init__(self, q):
self.list = q
def __add__(self, other):
return Base(self.list + other.list) # new Base obj
def __copy__(self):
copiedlist = self.list[:]
return Base(copiedlist)
x = Base([1,2])
y = Base([2,4,3])
z = x + y
Since x + y produces a *new* Base object, this can simply be
assigned to z without the need to make a copy.
Hamish Lawson
* Sent from RemarQ http://www.remarq.com The Internet's Discussion Network *
The fastest and easiest way to search and participate in Usenet - Free!
More information about the Python-list
mailing list