[Tutor] Overloading the assignment operator in a class
jordangreenberg at gmail.com
Wed Sep 20 23:22:38 CEST 2006
Carroll, Barry wrote:
> 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?
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:
etc, etc. We don't do this is python. Instead we assign an *object* to
so that myDie is a name for the Die object you've just created.
But you can also do this in python:
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,
More information about the Tutor