2 Replies - 733 Views - Last Post: 30 April 2012 - 12:12 PM Rate Topic: -----

#1 jone kim  Icon User is offline

  • New D.I.C Head

Reputation: 2
  • View blog
  • Posts: 46
  • Joined: 07-January 10

how to insert list while instantiating a class

Posted 30 April 2012 - 08:45 AM

I want to insert a list of values when instantiating an object for a class. for example;
I've a class marks and i want to insert marks for the class as a list of items like:
m1 = marks(1,2,3,4,5,5)

how can I do it? these values should be in a list, how can I do it?

class marks:
marksList = [] ## the inserted values when instantiating should go to this list
Is This A Good Question/Topic? 0
  • +

Replies To: how to insert list while instantiating a class

#2 Simown  Icon User is offline

  • Blue Sprat
  • member icon

Reputation: 319
  • View blog
  • Posts: 650
  • Joined: 20-May 10

Re: how to insert list while instantiating a class

Posted 30 April 2012 - 09:14 AM

If I understand you correctly, you want something like this:

class Marks:
    def __init__(self, *marks):
        # Assign marksList to a list of the supplied arguments from a tuple
        self.marksList = list(marks)



Python makes this easy because *marks will take an arbitrary amount of arguments. Some examples:
>>> m1 = Marks(1, 2, 3, 4, 5)
>>> m1
<__main__.Marks instance at 0x02D5B508>
>>> m1.marksList
[1, 2, 3, 4, 5]
...
>>> m2 = Marks(10, 9)
>>> m2.marksList
[10, 9]
...
>>> m3 = Marks(9, 8, 7, 6, 5, 4, 3, 2, 1, -1, -2, -3, -4, -5, -6)
>>> m3.marksList
[9, 8, 7, 6, 5, 4, 3, 2, 1, -1, -2, -3, -4, -5, -6]


Was This Post Helpful? 1
  • +
  • -

#3 atraub  Icon User is offline

  • Pythoneer
  • member icon

Reputation: 759
  • View blog
  • Posts: 2,010
  • Joined: 23-December 08

Re: how to insert list while instantiating a class

Posted 30 April 2012 - 12:12 PM

If the values are already in a list, you'd pass it in just like any other variable

class Marks:
    def __init__(self, marks):
        self.marksList = marks

x =  [1,2,3,4]
m1 = Marks(x)


Was This Post Helpful? 0
  • +
  • -

Page 1 of 1