return same type of object

Bruno Desthuilliers bdesth.quelquechose at
Wed Oct 25 00:28:00 CEST 2006

David Isaac a écrit :
> Bruno wrote:
>>This is usually known as a 'factory method'. You do realise that both
> solutions are *not* strictky equilavent, do you?
> Your point I believe is that after inheritance the factory method
> in the subclass will still
> return MyClass()
> but will return an instance of the subclass if I
> return self.__class__()
> Right.


> You did not comment further so I take it your view is that
> each is fine, pick the one that gives the behavior you want.

I did not comment because I don't know which behaviour is appropriate in 
*your* case.

> But Steve suggests going with the latter.

That's what I'd do too a priori.

> Here is an (very crude) argument for going with the latter:
> if you know you want an instance of MyClass(),
> you can do that directly,

Sure, but that's another point. If you want an instance of a subclass of 
MyClass, you can also do that directly !-)

MVHO is that in most cases, one would expect such a factory method to 
play nicely with subclassing. But as I said, this is not a hard rule.

More information about the Python-list mailing list