Feeding differeent data types to a class instance?
Steve Holden
steve at holdenweb.com
Sun Mar 14 09:03:53 EDT 2010
kuru 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)
>
> I want this class to accept multiple data types but process them as
> they are same when the classs deals with the instances.
>
> thanks
>
>
With your existing class you can use Python's ability to transform a
list or tuple into individual arguments using the * notation:
>>> class Vector:
... def __init__(self,x,y,z):
... self.x=x
... self.y=y
... self.z=z
...
>>> vl = [1, 2, 3]
>>> v = Vector(*vl)
>>> v.x
1
>>> v.y
2
>>> v.z
3
>>>
Will this do? It seems much simpler than rewriting an already
satisfactory class.
regards
Steve
--
Steve Holden +1 571 484 6266 +1 800 494 3119
See PyCon Talks from Atlanta 2010 http://pycon.blip.tv/
Holden Web LLC http://www.holdenweb.com/
UPCOMING EVENTS: http://holdenweb.eventbrite.com/
More information about the Python-list
mailing list