Question about isinstance()
Dave Benjamin
ramen at lackingtalent.com
Thu Jan 26 13:28:01 EST 2006
On Thu, 26 Jan 2006, Mr.Rech wrote:
> I've read some thread about isinstance(), why it is considered harmful
> and how you can achieve the same results using a coding style that
> doesn't break polymorphism etc... Since I'm trying to improve my Python
> knowledge, and I'm going to design a class hierarchy from scratch, I'd
> like to have some feedback about this from those of you much more
> experienced than me in OOP.
When trying to write OO code, you should of course always be suspicious of
any use of "isinstance". However, it is not always "considered harmful",
and this is one case where it is perfectly reasonable.
> Now, avoiding isinstace() I've written the following code:
>
> class foo(object):
> ...
> def __eq__(self, other):
> try:
> return self.an_attribute == other.an_attribute
> except AttributeError:
> return False
You were better off with what you had before. Equality in this case is
left completely open-ended, and as a result, there is no way that you can
guarantee that "a == b" is the same as "b == a" if "a" is a "foo" and "b"
is of unknown type. This can lead to bizarre and unpredictable behavior.
--
.:[ dave benjamin -( ramen/sp00 )- http://spoomusic.com/ ]:.
"To attain knowledge, add things every day.
To attain wisdom, remove things every day." - Lao Tzu
More information about the Python-list
mailing list