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
how to insert list while instantiating a class
Page 1 of 12 Replies - 539 Views - Last Post: 30 April 2012 - 12:12 PM
Replies To: how to insert list while instantiating a class
#2
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:
Python makes this easy because *marks will take an arbitrary amount of arguments. Some examples:
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]
#3
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)
Page 1 of 1
|
|

New Topic/Question
Reply




MultiQuote





|