type conversion

Benjamin Kaplan benjamin.kaplan at case.edu
Thu Jan 1 00:30:43 CET 2009


On Wed, Dec 31, 2008 at 5:26 PM, Steven D'Aprano <
steve at remove-this-cybersource.com.au> wrote:

> On Wed, 31 Dec 2008 12:35:20 -0800, Hamish McKenzie wrote:
>
> > sometimes I want to be able to initialize an instance with a variety of
> > different data types.
>
> Type conversion is a bit of a misleading subject line. You're not really
> converting different types, just initialising from different types.
>
>
> > as an obvious example I might want to initialize a 4x4 matrix with
> > either 16 floats, a list/tuple or 16 floats, another matrix or a
> > quaternion.
> >
> > is there any other way to do it other than putting case statements in
> > the __init__ method of the class, or having a Matrix.FromQuaternion(
> > quat )?
>
>
> You could have an external function qtom:
>
> def qtom(quaternion):
>    a, b, c, d = quaternion
>    return Matrix([
>        a, 0, 0, 0,
>        0, b, 0, 0,
>        0, 0, c, 0,
>        0, 0, 0, d])
>
>
> But the first two solutions seem reasonable to me, except of course
> Python doesn't have a case statement you have to use an if...elseif block.


You could also use a dict with type:method key/value pairings. This is
closer to a switch/case than an if...elif chain is.
(untested)

def __init__(self, *args) :
    inits = {list: self._init_from_list,
                float: self._init_from_floats,
                Matrix: self._init_from_matrix} #and so on
    inits[type(args[0])](*args)




>
>
> --
> Steven
> --
> http://mail.python.org/mailman/listinfo/python-list
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20081231/484db338/attachment.html>


More information about the Python-list mailing list