Feeding differeent data types to a class instance?

Rhodri James rhodri at wildebst.demon.co.uk
Sun Mar 14 01:54:40 CET 2010


On Sun, 14 Mar 2010 00:34:55 -0000, kuru <maymunbeyin at gmail.com> wrote:

> Hi
>
> I have couple classes in the form of
>
> class Vector:
>   def __init__(self,x,y,z):
>    self.x=x
>    self.y=y
>    self.z=z
>
> This works fine for me. However I want to be able to provide a list,
> tuple as well as individual arguments like below
>
> myvec=Vector(1,2,3)
>
> This works well
>
>
> However I  also want to be able to do
>
> vect=[1,2,3]
>
> myvec=Vec(vect)

You can do something like:

class Vector(object):
   def __init__(self, x, y=None, z=None):
     if isinstance(x, list):
       self.x = x[0]
       self.y = x[1]
       self.z = x[2]
     else:
       self.x = x
       self.y = y
       self.z = z

but this gets messy quite quickly.  The usual wisdom these days is to  
write yourself a separate class method to create your object from a  
different type:

class Vector(object):
   ... def __init__ as you did before ...

   @classmethod
   def from_list(cls, lst):
     return cls(lst[0], lst[1], lst[2])

vect = [1,2,3]
myvec = Vector.from_list(vect)


-- 
Rhodri James *-* Wildebeeste Herder to the Masses



More information about the Python-list mailing list