<br><br><div class="gmail_quote">On Wed, Dec 31, 2008 at 5:26 PM, Steven D'Aprano <span dir="ltr"><<a href="mailto:steve@remove-this-cybersource.com.au">steve@remove-this-cybersource.com.au</a>></span> wrote:<br>
<blockquote class="gmail_quote" style="border-left: 1px solid rgb(204, 204, 204); margin: 0pt 0pt 0pt 0.8ex; padding-left: 1ex;">On Wed, 31 Dec 2008 12:35:20 -0800, Hamish McKenzie wrote:<br>
<br>
> sometimes I want to be able to initialize an instance with a variety of<br>
> different data types.<br>
<br>
Type conversion is a bit of a misleading subject line. You're not really<br>
converting different types, just initialising from different types.<br>
<br>
<br>
> as an obvious example I might want to initialize a 4x4 matrix with<br>
> either 16 floats, a list/tuple or 16 floats, another matrix or a<br>
> quaternion.<br>
><br>
> is there any other way to do it other than putting case statements in<br>
> the __init__ method of the class, or having a Matrix.FromQuaternion(<br>
> quat )?<br>
<br>
<br>
You could have an external function qtom:<br>
<br>
def qtom(quaternion):<br>
    a, b, c, d = quaternion<br>
    return Matrix([<br>
        a, 0, 0, 0,<br>
        0, b, 0, 0,<br>
        0, 0, c, 0,<br>
        0, 0, 0, d])<br>
<br>
<br>
But the first two solutions seem reasonable to me, except of course<br>
Python doesn't have a case statement you have to use an if...elseif block.</blockquote><div><br>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.<br>
(untested)<br><br>def __init__(self, *args) :<br>    inits = {list: self._init_from_list,<br>                float: self._init_from_floats,<br>                Matrix: self._init_from_matrix} #and so on<br>    inits[type(args[0])](*args)<br>
<br><br><br></div><blockquote class="gmail_quote" style="border-left: 1px solid rgb(204, 204, 204); margin: 0pt 0pt 0pt 0.8ex; padding-left: 1ex;"><br>
<br>
<br>
--<br>
Steven<br>
<font color="#888888">--<br>
<a href="http://mail.python.org/mailman/listinfo/python-list" target="_blank">http://mail.python.org/mailman/listinfo/python-list</a><br>
</font></blockquote></div><br>