2

From the "Fluent Python" book, it says:

However, even with ABCs, you should beware that excessive use of isinstance checks may be a code smell—a symptom of bad OO design. It’s usually not OK to have a chain of if/elif/elif with insinstance checks performing different actions depending on the type of an object: you should be using polymorphism for that—i.e., designing your classes so that the interpreter dispatches calls to the proper methods, instead of you hardcoding the dispatch logic in if/elif/elif blocks.

Now, there are many SO questions on how to replace if/elif/elif blocks, and a lot of answers are using dictionaries etc etc. But it's not what the paragraph suggesting

designing your classes so that the interpreter dispatches calls to the proper methods

Does it mean the following approach?

class Artist:
    def draw(self): ...

class Gunslinger:
    def draw(self): ...

class Lottery:
    def draw(self): ...

The dispatcher just calls:

def draw_dispatcher(obj):
    obj.draw()

Are there any other ways?

smci
  • 32,567
  • 20
  • 113
  • 146
James Lin
  • 25,028
  • 36
  • 133
  • 233
  • 1
    Yes and yes. (But why the extra `draw_dispatcher` function, when `obj.draw()` suffices?) I'm not sure if this Q is too broad or not... or a [duplicate](http://stackoverflow.com/questions/2835793/how-does-polymorphism-work-in-python). – cfi Sep 22 '16 at 07:32
  • @cfi the `draw_dispatcher` was just demonstrating dependency injection. – James Lin Apr 16 '20 at 23:29

0 Answers0