Feeding differeent data types to a class instance?

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

  1. kuru

    kuru Guest


    I have couple classes in the form of

    class Vector:
    def __init__(self,x,y,z):

    This works fine for me. However I want to be able to provide a list,
    tuple as well as individual arguments like below


    This works well

    However I also want to be able to do



    I want this class to accept multiple data types but process them as
    they are same when the classs deals with the instances.

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

    Steve Holden, Mar 14, 2010
  4. kuru

    kuru Guest


    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

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