Return the different child object depending on the condition using the same method
<p>I have a two child classes which are inherited from the base class. I have one method in the different script which will actually return one of the child class object depending on some condition, is it the correct way in python to return the different child object using the same method. I think yes as their type is same and they are inherited from the same base class? Or should type casting be done? Please guide the below example is just for explaining the question in simple terms.</p>

<pre><code>class A():

class B(A):
   Different methods

class C(A):
   Different methods
</code></pre>

<p>Other Script: </p>

<pre><code>def test_func:
   if &lt;some-condition&gt;
      new_obj = B()
   else
      new_obj = C()
   return new_obj
</code></pre>

<p>Python is a dynamically typed language. One does not declare types. So, from that side, it is perfectly fine to pass arguments and return values of any type.</p>

<p>On the other hand, you want your objects to be usable, so some interface has to be adhered to. For example, you can often pass any object with <code>read</code> and <code>readline</code> methods instead of an opened file. That is not only acceptable, but actually one of the strong advantages of Python over some other languages.</p>

<p>In this question, the case is even cleaner than what is usually done in Python. This pattern is valid even in e.g. much stricter C++ (see <a href="http://stackoverflow.com/questions/4665117/c-virtual-function-return-type">this question</a>).</p>

<p><strong>TL;DR:</strong></p>

<p>Yes, it is fine. It would even be fine without inheriting from <code>A</code>, as long as <code>B</code> and <code>C</code> looked and behaved (and <a href="https://en.wikipedia.org/wiki/Duck_test" rel="nofollow">quacked</a>) similarly enough for the code using <code>test_func</code> to work.</p>

python