Feeding differeent data types to a class instance?

Discussion in 'Python' started by kuru, Mar 14, 2010.

  1. kuru

    kuru Guest

    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
     
    kuru, Mar 14, 2010
    #1
    1. Advertisements

  2. The usual term for this is "polymorphism".
    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 D'Aprano, Mar 14, 2010
    #2
    1. Advertisements

  3. kuru

    Steve Holden Guest

    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
    ....
    Will this do? It seems much simpler than rewriting an already
    satisfactory class.

    regards
    Steve
     
    Steve Holden, Mar 14, 2010
    #3
  4. kuru

    kuru Guest

    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
     
    kuru, Mar 14, 2010
    #4
    1. Advertisements

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 (here). After that, you can post your question and our members will help you out.