Andrew Lee a écrit :
(snip)
as a rule of thumb .. if you are using "isinstance" in a class to determine what class a parameter is ... you have broken the OO contract.

Nope.

Remember, every class ought to have a well defined internal state and a well defined interface to its state.

I don't see how the part about the internal state relates to the problem here.


If I write --

class foo (object):
   def __init__ :
      pass

   def some_func (self, val) :
      if isinstance (val, "bar") :
    ....

Then I am either doing something very wrong

If you do so in a desperate attempt to emulate static typing in Python, then yes, you're doing something very wrong. Else:

or very clever

Not necessarily. Given Python's dynamic typing, there's no builtin OneObviousWay(tm) way to dispatch on different functions based on argument's type - something often done in statically typed OOPLs using method overridding (ie: different methods with same name but different signatures). Doing a manual dispatch based on argument's type, while not good OO style, is sometimes the simplest working solution, and a good enough one for the problem at hand. Having different methods for different arg types has the drawback that you don't have one single generic function/method that you can use as a callback.

Having a real multidispatch (or rule-based dispatch etc) system either builtin or in the stdlib would indeed be much cleaner. Until then, there are a couple third-part packages solving this problem, but it can be overkill for simple problems (and add unneeded/unwanted dependencies).

my 2 cents.
--
http://mail.python.org/mailman/listinfo/python-list

Reply via email to