type conversion

Robert Kern robert.kern at gmail.com
Thu Jan 1 17:40:32 EST 2009


Hamish McKenzie wrote:
> sometimes I want to be able to initialize an instance with a variety of different data 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 )?

I recommend keeping the __init__() as dumb as possible. Ideally, it should just 
assign to attributes. I would add a from<foo>() classmethod for each <foo> that 
I wanted to support. If I really wanted an all-singing, all-dancing 
initialization method, I would add another classmethod that would just dispatch 
to the appropriate type-specific classmethod. I prefer classmethods to plain 
functions because I can subclass.

-- 
Robert Kern

"I have come to believe that the whole world is an enigma, a harmless enigma
  that is made terrible by our own mad attempt to interpret it as though it had
  an underlying truth."
   -- Umberto Eco




More information about the Python-list mailing list