469,609 Members | 1,652 Online
Bytes | Developer Community
New Post

Home Posts Topics Members FAQ

Post your question to a community of 469,609 developers. It's quick & easy.

Re: Overloading operators

On Wed, 15 Oct 2008 14:34:14 +0200, Mr.SpOOn wrote:
in a project I'm overloading a lot of comparison and arithmetic
operators to make them working with more complex classes that I defined.
What is the best way to do this? Shall I use a lot of "if...elif"
statements inside the overloaded operator? Or is there a more pythonic
and dynamic way?
Something that is more pythonic is something that doesn't use
multimethods. It's just an elaborated way to do type checking. In python,
you usually avoid type checking and if-elif-block-with-isinstance in
favor of Duck Typing and EAFP (Easier to Ask Forgiveness than Permission,
i.e. try-block).
Sometimes I need a different behavior of the operator depending on the
argument. For example, if I compare a object with an int, I get a
result, but if I compare the same object with a string, or another
object, I get another result.
*smells a bad class design* If that is the case, I'd recommend on
splitting that behavior into two or more functions/operators (or possibly
splitting the class). It's hard to reason the behavior of a class if the
class is that complex (Simple is better than complex; Complex is better
than complicated. The Zen of Python this:2-3).

Oct 16 '08 #1
0 601

This discussion thread is closed

Replies have been disabled for this discussion.

Similar topics

13 posts views Thread by denis wendum | last post: by
2 posts views Thread by bq | last post: by
20 posts views Thread by KL | last post: by
18 posts views Thread by uday | last post: by
5 posts views Thread by Jerry Fleming | last post: by
3 posts views Thread by johnmmcparland | last post: by
15 posts views Thread by PengYu.UT | last post: by
7 posts views Thread by Rahul | last post: by
2 posts views Thread by jimzat | last post: by
reply views Thread by Solution2021 | last post: by
reply views Thread by devrayhaan | last post: by
By using this site, you agree to our Privacy Policy and Terms of Use.