Feeding differeent data types to a class instance?

K

kuru

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
 
S

Steven D'Aprano

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.
 
S

Steve Holden

kuru said:
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:
.... 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
 
K

kuru

Hi

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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,053
Latest member
BrodieSola

Latest Threads

Top