Newbie Question - Overloading ==
Lie.1296 at gmail.com
Sat Apr 5 01:49:36 CEST 2008
On Apr 1, 2:22 pm, Duncan Booth <duncan.bo... at invalid.invalid> wrote:
> "bruno.desthuilli... at gmail.com" <bruno.desthuilli... at gmail.com> wrote:
> >> Surely an A isn't equal to every other object which just happens to
> >> have the same attributes 'a' and 'b'?
> > And why not ?-)
> >> I would have thoughts the tests want to be
> >> something like:
> >> class A:
> >> def __eq__(self,other):
> >> return (isinstance(other, A) and
> >> self.a == other.a and self.b == other.b)
> >> (and similar for B) with either an isinstance or exact match required
> >> for the type.
> > I don't think there's a clear rule here. Python is dynamically typed
> > for good reasons, and MHO is that you should not fight against this
> > unless you have equally good reasons to do so.
> I fully agree with that, but an apple != a pear, even if they are the same
> size and colour. There will be some types where you can have equality
> between objects of different types (e.g. int/float), but more often the
> fact that they are different types wil automatically mean they are not
Even though an apple != a pear, sometimes when we just don't need to
care between their differences we can treat them as equal, that's what
duck typing is. It really depends on your need if you decided to use
or not to use isinstance checking, in most cases you'd want them to be
checked, but sometimes you just want to know whether the two objects
has the same values on their relevant attributes.
More information about the Python-list