How do I overload 'equals'?

Diez B. Roggisch deets_noospaam at web.de
Mon Feb 2 15:08:10 EST 2004


> aHouse = makeAhouse()
> aHouse superAssign myHouse # use the superAssign operator
> 
> to fill aHouse with all the objects inside myHouse
> and then call an arbitray method:
> myHouse.log('aHouse has a copy of your stuff')
> 
> Is this possible?

First of all, write the operator as simple function with two arguments, your
aHouse and myHouse:

def init_house(aHouse, myHouse):
  aHouse.inhabitants = myHouse.inhabintants
  ....

Now if you actually have different functions, depending on the actual types
you use, you could go for multimethod-dispatch and create a HouseAssigner
like this:

class HouseAssigner(multimethods.Dispatch):
    def __init__(self):
        multimethods.Dispatch.__init__(_)
        _.add_rule((AHouse, MyHouse), _.init_house)

I assumed that aHouse is of tpye AHouse, and myHouse of MyHouse

Now you can create an instance of HouseAssigner and use that to perform the
actual assignment:

ha = HousAssigner()
ha(aHouse, myHouse)

Now for the operator-stuff: My c++-skills are somewhat rusted (something I'm
not sure if to be glad of or not), so I don't remember how to exactly
declare a custom assignment-operator. 

However, I think that you are after a thing here that I personally would
consider as bad style: Usually, polymorphism is used to write code that is
not interested in details of some actual object, but works on abstract
concepts. An example would be a ParkController working on Car-objects, but
you feed it with Porsche, Mercedes and BMW-objects (which inherit from Car,
of course). Still the actual car knows about its unique features.

Introducing an assignment operator like you want it to have now acutally
performs willingly a slicing-operation - the object forgots something about
what its capable/consisting of. I don't see any reason for that - it might
even lead to severe problems, as accidential slicing in c++ does.

So - maybe you could fill in what actual use-case you have for such a
behaviour.

Another thing to mention might be that assignment in python is different
from assignment in C/C++: 

c = Car()

only means that the identifier c now points to an instance of Car - not that
c is of type car. So in the next line, you could say:

c = 10

Others have explained that behaviour better, you might find informations in
the documentation.

Regards,

Diez




More information about the Python-list mailing list