Converting between objects

Bjoern Schliessmann usenet-mail-0306.20.chr0n0ss at spamgourmet.com
Thu Jul 19 22:33:23 CEST 2007


Nathan Harmston wrote:

> is there way I can define conversion functions like this:
> 
> say i have a class A and a class B
> 
> bobj = B()
> aobj = a(bobj)
> 
> in a neater way than just defining a set of methods
> 
> def a(object_to_convert)
>     # if object_to_convert of type......
>     # do some stuff
>    return A()
> 
> def b(object_to_convert)
>     # if object_to_convert of type......
>     # do some stuff
>    return B()
> 
> Cause this seems a little verbose and not very OO.

Yes, simply write something like

class a(object):
    def __init__(self, parameter):
        if isinstance(parameter, B):
            # conversion from B to a
        else:
            # something else

Something like that is called "conversion constructor". At least in
C++.

Regards,


Björn

-- 
BOFH excuse #55:

Plumber mistook routing panel for decorative wall fixture




More information about the Python-list mailing list