return an object of a different class

Jean-Michel Pichavant jeanmichel at
Mon Feb 21 14:23:10 CET 2011

alex23 wrote:
> Jean-Michel Pichavant <jeanmic... at> wrote:
>> You simply don't return inconsistent types with a return statement. This
>> is a general rule in programming that has probably exceptions but
>> regarding what you're saying, you clearly don't want to do that.
> I don't think they were intended to be inconsistent types, but
> subclasses of the same type. Returning different subclasses is exactly
> what a factory is for. And given Python's propensity for duck typing,
> they don't even really need to be subclassed for the same object, they
> just need the interface that is required.
>> Immagine the following code:
>> oNumber = MyNumbers( # note that oNumber is not a
>> MyNumbers instance... quite confusing don't you think ?
>> oNumber. ... wait a minute, which methods am I allowed to call ???
>> SmallNumbers adn BigNumbers have differents methods.
> What if they have different implementations rather than methods?
The answer is quite simple, from a OOP POV, the factory class/function 
returns a MyNumber instance, not a SmallNumber nor BigNumber one. This 
is what the documentation should state. Note that SmallNumber and 
BigNumber instances are both MyNumber instances. But from a user POV, 
there's no need to know about Small and Big implementations. All you 
need to know is the base classe MyNumber methods.

Regarding duck typing, it is all about implementing an interface that is 
not explicit. That way, factory functions return consistent types if 
they return instances with a common interface. That's perfectly legit.

What is not legit, is to return different objects for which the caller 
has to test the type to know what attributes he can use.


More information about the Python-list mailing list