Saturday, 24 August 2013

argument unpacking and assignment to class variables

argument unpacking and assignment to class variables

Hi I have the following code, which attempts to create an instance of a
class and assign argument values to it. I am trying to use *args to do
this as follows:
def main():
testdata = ['FDR', False, 4, 1933]
apresident = President(testdata)
print apresident
print apresident.alive
class President:
id_iter = itertools.count(1)
#def __init__(self, president, alive, terms, firstelected):
def __init__(self, *args):
self.id = self.id_iter.next()
self.president = args[0]
self.alive = args[1]
self.terms = args[2]
self.firstelected = args[3]
I get a "tuple index out of range" error. As you can see from the
commented line, I was previously using positional arguments to accomplish
this (which worked), and used lines like the following to do it:
self.president = president
What is the right way to use *args in this case? should I be using *kwargs?

No comments:

Post a Comment