Note that there are some explanatory texts on larger screens.

plurals
  1. POIssue with python class hierarchy
    primarykey
    data
    text
    <p>I have a class hierarchy:</p> <pre><code>class ParentClass: def do_something(self): pass # child classes have their own implementation of this class ChildClass1(ParentClass): def do_something(self): &lt;implementation here&gt; class ChildClass2(ParentClass): def do_something(self, argument_x): &lt;implementation here&gt; class ChildClass3(ParentClass): def do_something(self, argument_y): &lt;implementation here&gt; </code></pre> <p>There are two problems here:</p> <ul> <li>method do_something() has different interfaces in subclasses: it accepts an argument in child classes 2 and 3, but has no argument in child class 1</li> <li>the arguments of do_something() have different names to emphasize that they have different meanings in child classes 2 and 3. This will become clearer below, from the usage example</li> </ul> <p>This is how the classes are used:</p> <p>There is a factory class that returns instances:</p> <pre><code>class ChildFactory: def get_child(self, argument): if argument == '1': return ChildClass1() elif argument == '2': return ChildClass2() elif argument == '3': return ChildClass3() </code></pre> <p>later in code:</p> <pre><code>... # pseudocode, not python child_type = ? # can have values '1', '2' or '3' at this moment var1 = 1 var2 = 'xxx' # var1 and var2 have different types, just to emphasize the difference in their # meaning when being passed as arguments to do_something() # this was mentioned above (the second problem) child = ChildFactory.get_child(child_type) if child is an instance of ChildClass1, child.do_something() is called if child is an instance of ChildClass2, child.do_something(var1) is called if child is an instance of ChildClass3, child.do_something(var2) is called # end of pseudocode </code></pre> <p>Questions:</p> <ol> <li>Are the two problems mentioned above a sign of a bad design? If so, what's the correct way to design the hierarchy?</li> <li>How to write the pseudocode snippet uniformly in python? The main concern is to avoid using a huge if/else statement for each particular case, because it will double the if/else statement from ChildFactory.get_child()</li> </ol>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload