[Tutor] assinging to object attributes from file input

Jeff Shannon jeff@ccvcorp.com
Thu Apr 10 15:48:03 2003

Chris Somerlot wrote:

> What is the best way to assign values read in from a file to object 
> attributes? Make my objects in a class with null values and then use a 
> function to read the file and assign to the object?

Depends on how the file is laid out, and what the attributes are like. 
 I tend to like using __init__() to do this, either by passing it an 
entire line (if the file is, say, fixed-width columns, I can encapsulate 
column widths within the class too), or by splitting the line on the 
field-separator (tab, comma, whatever) and then passing in the list of 
values.  But using __init__() may imply that I'll only be creating 
instances of this class from lines in this (type of) file.  Under other 
circumstances (instances may come from a variety of sources with a 
variety of optional attributes), it may make more sense to do as you 
mention, initializing "empty" instances and then assign attributes to 
them as needed.

Jeff Shannon
Credit International