[Tutor] how to initialize a class with arbitrary argument list from a file?

Kent Johnson kent37 at tds.net
Fri Mar 18 13:43:04 CET 2005


Christian Meesters wrote:
> Hi
> 
> How can I initialize a class like this from a file:
> class Some:
>     def __init__(self,data,axis,**kwargs):
>         pass
> 
> 'data' and 'axis' should be lists of floats. Meta data can be passed to 
> kwargs like 'name="name",date="2/3/05",...'.
> Right now the return value of my function reading the file looks like this:
> dummy = fromFile(path)
> print dummy
> [[[datalist],[axislist],'name="name"','date="2/3/05"',...],...]

Something like this (untested):

allSome = []
for args in dummy:
   # args looks like [[datalist],[axislist],'name="name"','date="2/3/05"',...]
   datalist = args[0]
   axislist = args[1]
   kwargs = {}
   for kv in args[2:]:
     # kv looks like 'name="name"'
     k, v = kv.split('=')
     kwargs[k] = v.strip('"')
     # You may need more sophisticated processing of v
     # and more error detection, depending on the details of the data...
   some = Some(datalist, axislist, **kwargs)
   allSome.append(some)

Kent



More information about the Tutor mailing list