473,939 Members | 7,946 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

How do I overload 'equals'?

Hi there,

I just figured out how to use __add__() to overload the "+" operator
for objects of a class.

According to googel queries, I see other functions available to me for
overloading other operators:

__mul__(), __sub__(), ...

I was hoping to overload "=" or use some string to do assignment with
side effects.

For example,

obj1 = ClassX('green')
obj2 = ClassX('red')

obj1 superEqual obj2

I'd like to be able to control the behavior of the superEqual operator
such that it does assignment with side effects.

For example, maybe it would do this:

obj = obj2
incrementEquali tyCounter()
addAuditRecordT oDB()

How do I do this in Python?

-moi
Jul 18 '05 #1
6 12066
Equis Uno said the following on 02/02/2004 11:52 AM:
Hi there,

I just figured out how to use __add__() to overload the "+" operator
for objects of a class.

According to googel queries, I see other functions available to me for
overloading other operators:

__mul__(), __sub__(), ...

I was hoping to overload "=" or use some string to do assignment with
side effects.

For example,

obj1 = ClassX('green')
obj2 = ClassX('red')

obj1 superEqual obj2

I'd like to be able to control the behavior of the superEqual operator
such that it does assignment with side effects.

For example, maybe it would do this:

obj = obj2
incrementEquali tyCounter()
addAuditRecordT oDB()

How do I do this in Python?


Overloading operators is explained in
http://python.org/doc/2.3.3/lib/modu...r.html#l2h-490

Maybe you are looking for __eq__? After overloading it, you may
say:
if obj1 == obj2:
...
From what you wrote I think you want to overload the assign operator
(single =) . This is not supported in Python directly, but you may take
a look at descriptors:
http://users.rcn.com/python/download/Descriptor.htm

Regards
Mirko
--
Jul 18 '05 #2
On Monday 02 February 2004 11:36 am, Mirko Zeibig wrote:
Equis Uno said the following on 02/02/2004 11:52 AM:
Hi there,

I just figured out how to use __add__() to overload the "+" operator
for objects of a class.

According to googel queries, I see other functions available to me for
overloading other operators:

__mul__(), __sub__(), ...

I was hoping to overload "=" or use some string to do assignment with
side effects.

For example,

obj1 = ClassX('green')
obj2 = ClassX('red')

obj1 superEqual obj2

I'd like to be able to control the behavior of the superEqual operator
such that it does assignment with side effects.

For example, maybe it would do this:

obj = obj2
incrementEquali tyCounter()
addAuditRecordT oDB()

How do I do this in Python?


Overloading operators is explained in
http://python.org/doc/2.3.3/lib/modu...r.html#l2h-490

Maybe you are looking for __eq__? After overloading it, you may
say:
if obj1 == obj2:
...
From what you wrote I think you want to overload the assign operator
(single =) . This is not supported in Python directly, but you may take
a look at descriptors:
http://users.rcn.com/python/download/Descriptor.htm


Descriptors, or just defining good old fashioned __getattr__
(http://www.python.org/doc/current/re...e-access.html), can only
overload assignment to attributes.

Changing the meaning of "=", as I believe you want to do, is the kind of
change to the syntax of the language that Python by design does not allow in
order to maintain consistency across different people's code (and no doubt
for lots of other good reasons). If you really want to do this perhaps you'd
be better off using Io <wink>. Otherwise you'll have to settle for defining
a function "superEqual " (or better "superAssig n", since"=" is an assignment
operator not an equality operator.)

James
--
James Henderson, Logical Progression Ltd.
http://www.logicalprogression.net/
http://sourceforge.net/projects/mailmanager/
Jul 18 '05 #3
ok,

So I can't overload '='.
Fair enough.

How do I create/define an operator for a class of objects?

For example,

I'd like these statements:

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('aH ouse has a copy of your stuff')

Is this possible?

-moi
Jul 18 '05 #4
> 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('aH ouse 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(aHou se, myHouse):
aHouse.inhabita nts = myHouse.inhabin tants
....

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(m ultimethods.Dis patch):
def __init__(self):
multimethods.Di spatch.__init__ (_)
_.add_rule((AHo use, 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

Jul 18 '05 #5
Diez,

your info about the 'multimethod-dispatch House Assigner' is kewl.
It's not what I'm currently looking for but I may in the future.

I have no use case.

My motivation is to learn about the limitations and capability of Python.

We could call it a useless case.

I suspect that building an operator with un-obvious side effects
is bad programming style.

It's better to just use a simple function to do the assignment:
aHouse = superAssign (myHouse)

If I want to know what superAssign() does, I go read it.

I'd still like to build an arbitrary operator though.

-moi
"Diez B. Roggisch" <de************ @web.de> wrote in message news:<bv******* ******@news.t-online.com>...
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('aH ouse 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(aHou se, myHouse):
aHouse.inhabita nts = myHouse.inhabin tants
....

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(m ultimethods.Dis patch):
def __init__(self):
multimethods.Di spatch.__init__ (_)
_.add_rule((AHo use, 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

Jul 18 '05 #6
> My motivation is to learn about the limitations and capability of Python.

That is easy, Python can't do it.
We could call it a useless case.
So why bother? Oh yeah, "to learn about the limitations and capability
of Python".
I suspect that building an operator with un-obvious side effects
is bad programming style.
Of course. Building a comparison operator that creates arbitrary
attributes on an argument is one, of many, examples of bad programming
style.
It's better to just use a simple function to do the assignment:
aHouse = superAssign (myHouse)
I don't think that would do what you want. All that would do is assign
the name aHouse a reference to whatever is returned by
superAssign(myH ouse). You aren't modifying what aHouse used to reference.
I'd still like to build an arbitrary operator though.


It is not possible for all operators. For a list of those operators
that you /can/ overload, check the 'operator' module.

- Josiah
Jul 18 '05 #7

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

1
2077
by: Piotre Ugrumov | last post by:
I'm following your help. I have written the overload of the operator <<. This overload work! :-) But I have some problem with the overload of the operator >>. I have written the overload of this least operator for the class Person, but I don't know how write the overload for a class that derived from the class Person. The overload of << in Person is this: ostream & operator<<(ostream &out, const Persona &p){ out<<p.getNome()<<"...
17
2530
by: Chris | last post by:
To me, this seems rather redundant. The compiler requires that if you overload the == operator, you must also overload the != operator. All I do for the != operator is something like this: public static bool operator !=(MyType x, MyType y) { return !(x == y); } That way the == operator handles everything, and extra comparing logic isn't
4
2551
by: Kurt | last post by:
Wouldn't you agree all of the follwoing should produce the same result? r = (o1 == o2); r = (o2 == o1); r = object.Equals(o1, o2); r = object.Equals(o2, o1); r = (o1.Equals(o2)); r = (o2.Equals(o1));
18
4776
by: JohnR | last post by:
From reading the documentation, this should be a relatively easy thing. I have an arraylist of custom class instances which I want to search with an"indexof" where I'm passing an instance if the class where only the "searched" property has a value. I expected to get the index into the arraylist where I could then get the entire class instance. However, the 'indexof' is never calling my overloaded, overrides Equals method. Here is the...
9
2399
by: Tony | last post by:
I have an operator== overload that compares two items and returns a new class as the result of the comparison (instead of the normal bool) I then get an ambiguous operater compile error when I attempt to check to see if the object is null: "The call is ambiguous between the following methods or properties: 'TestObject.operator ==(TestObject, string)' and 'TestObject.operator ==(TestObject, TestObject)" Does anyone have any idea how to...
12
2235
by: cody | last post by:
Why can I overload operator== and operator!= separately having different implementations and additionally I can override equals() also having a different implementation. Why not forbid overloading of == and != but instead translate each call of objA==objB automatically in System.Object.Equals(objA, objB). This would remove inconsistencies like myString1==myString2
7
2680
by: =?Utf-8?B?QWxleCBDb2hu?= | last post by:
In C++, there is an easy technique to provide an overloaded Equals() method. A straightforward translation to C# causes a stack overflow. Why does b.Equals(ba) in the snippet below not understand that it should call (ba as B).Equals(b) inside? Thanks in advance, Alex code sample follows:
5
3706
by: jknupp | last post by:
In the following program, if the call to bar does not specify the type as <int>, gcc gives the error "no matching function for call to ‘bar(A&, <unresolved overloaded function type>)’". Since bar explicitly takes a pointer-to-member with no parameters, why is the lookup for the overloaded function not able to use the number of arguments to determine the appropriate function? Is there a relevant portion of the standard that governs the...
10
1705
by: John Doe | last post by:
Hi, I am trying to transform a class with some time consuming operation by adding a thread. To be able to pass data to thread I have declared a class ThreadParam as shown below : class CProvisioning {
0
10134
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9963
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
11524
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
11109
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
9858
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
7384
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
6296
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
4447
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
3501
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.