[Tutor] Overloading the assignment operator in a class

Jordan Greenberg jordangreenberg at gmail.com
Wed Sep 20 23:22:38 CEST 2006


Carroll, Barry wrote:
> Greetings:
> 
> I have a class that implements a die (singular or dice).  Here is the class definition:
<SNIP a bunch of stuff>
> How do I overload the '=' operator to give the desired behavior?
> 
> Regards,
>  
> Barry

AFAIK, you can't. Unlike, say, Java or C++, the assignment operator is
not operating on an object, but instead a name. Consider:

in C++ we define variables to a type:

int myInt;
Die myDie;

etc, etc. We don't do this is python. Instead we assign an *object* to
an *name*

myInt=5
myDie=Die(6, 3)

so that myDie is a name for the Die object you've just created.
But you can also do this in python:

myDie="Some string"

Its not assigning to the myDie object, just the name myDie, so that now
myDie is a name for a string containing "Some String"
In other languages, its reasonable to think of variables as containers.
That thinking isn't valid in Python. In Python, what you'd think of as
'variables' are just names for objects. (If you know C++, think
pointers, sort of. myDie isn't the Die Object, its just a reference as
to where the object is. Assigning to a pointer doesn't change the
object, but what the pointer is pointing to.)

Hope this helps,
Jordan Greenberg


More information about the Tutor mailing list