Converting between objects

Ben Finney bignose+hates-spam at benfinney.id.au
Fri Jul 20 01:00:57 CEST 2007


"Nathan Harmston" <ratchetgrid at googlemail.com> writes:

> I have being thinking about this and was wondering with built in types
> you can do things like
> 
> float(1)

Calls the constructor for the 'float' type, passing the integer 1; the
constructor returns a new float object.

> str(200)

Calls the constructor for the 'str' type, passing the integer 200; the
constructor returns a new str object.

> is there way I can define conversion functions like this

These are not "conversion functions"; they are the constructors of the
corresponding types.

You can hook into the instance creation by modifying the '__new__'
method of the metaclass; but probably the easier way is to hook into
the instance initialisation (after it is created) by modifying the
'__init__' method of the class.

> 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()

Rather than this, define '__init__' to do some stuff to 'self', that
is, modify attributes of the instance during its initialisation. The
'__init__' method is automatically called during object initialisation
and receives all the parameters that were passed to the constructor.

    class B(object):
        def __init__(self, obj):
            self.foo = do_stuff(obj)

    aobj = B(42)

-- 
 \        "Pinky, are you pondering what I'm pondering?" "Wuh, I think |
  `\   so, Brain, but if we didn't have ears, we'd look like weasels." |
_o__)                                         -- _Pinky and The Brain_ |
Ben Finney



More information about the Python-list mailing list