Converting between objects

Bruno Desthuilliers bruno.42.desthuilliers at wtf.websiteburo.oops.com
Fri Jul 20 03:35:27 EDT 2007


Nathan Harmston a écrit :
> Hi,
> 
> I have being thinking about this and was wondering with built in types
> you can do things like
> 
> float(1) or str(200)
> 
> 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.

Just about the "not very OO" part: in Python, a class is a callable 
object - just like functions - that when called usually returns an 
instance of itself. IOW, a class is a Factory. So, from the client code 
POV, the fact that the factory is a class or function (both being 
callable objects) doesn't make any difference. Remember that OO is about 
objects, not about classes.

> Please correct me if I m wrong or offer me hints as to a better way to 
> do it ?

Others already answered the question. Note that if you need the factory 
to be able to return different subtypes based on it's argument or on 
some 'external' condition (platform, settings, whatever), you can also 
override the class '__new__' method, which is the real constructor 
(__init__ being the initialiser).



More information about the Python-list mailing list