constructing an object from another instance of the same class

Carl Banks pavlovevidence at gmail.com
Mon Jun 21 06:26:19 EDT 2010


On Jun 18, 3:55 pm, Christoph Groth <c... at falma.de> wrote:
> Bruno Desthuilliers <bruno.42.desthuilli... at websiteburo.invalid> writes:
> > Anyway: the simplest solution here is to replace the call to your Base
> > class with a call to a factory function. I'd probably go for something
> > like (Q&D untested code and other usual warnings) :
>
> > (...)
>
> Yeah, that will do what I want.
>
> My confusion arose from the expectation that there had to be some
> mechanism to do the conversion automatically.  But actually a simple
>
> def bar(arg):
>     if not isinstance(arg, Base):
>         arg = Base(arg)
>         # Do something with arg.
>
> is a simple and explicit solution of the problem.

What if someone wants to call bar with an argument that mimics a Base
but isn't a subclass?  Your function would try to convert it to an
actual Base.

Something to think about before you make a habit of this.


Carl Banks



More information about the Python-list mailing list