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
> 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
> I want this class to accept multiple data types but process them as they
> are same when the classs deals with the instances.
The usual term for this is "polymorphism".
> myvec=Vector(1,2,3)
>
> vect=[1,2,3]
> myvec=Vec(vect)
I assume you mean Vector in the last line.
I find this the easiest way to handle this situation:
class Vector(object, *args):
if len(args) == 1:
# Assume the caller passed a list argument.
args = args[0]
x, y, z = args # Unpack the arguments.
# then process as normal.
--
Steven
>>> 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/
Thank you so much for all these great suggestions. I will have time
today to try all these and see which one works best for me
cheers
Answers to your question have spread onto the Python blogosphere as
well.
http://pythonconquerstheuniverse.wordpress.com/2010/03/17/multiple-constructors-in-a-python-class/
http://blog.dowski.com/2010/03/17/my-take-on-multiple-constructors/
That second one is my response.
Christian