Elegant solution needed: Data manipulation

Scott David Daniels Scott.Daniels at Acm.Org
Thu Jan 31 07:52:44 CET 2002


On Wed, 30 Jan 2002 19:42:24 -0600, "Jason Orendorff" <jason at jorendorff.com> wrote:
> Mark wrote:
> ... lots of great suff...
> 
> # Step 1. Build your data structure out of objects.
> class DataRow:
>     def __init__(self, height, weight, speed):
>         self.height = height
>         self.weight = weight
>         self.speed = speed

I'd replace this with the following more general piece:
 class Data:
      def __init__(self, **kwargs):
          self.__dict__.update(kwargs)
      def __repr__(self):
          return ''.join((
              self.__class__.__name__, '(',
              ', '.join(['%s=%r' % entry for entry 
                      in vars(self).items()]), ')'))

> # You can write the part the reads it out of a file.
> # Here is what the resulting data structure should be.
> data = [ DataRow(3, 6, 12),
>          DataRow(5, 9, 20),
>          DataRow(4, 10, 15) ]
In which case you'll need this to be:
  data = [ Data(height=3, width=6, speed=12),
          Data(height=5, width=9, speed=20),
          Data(height=4, width=10, speed=15) ]

and everything else works the same way.
The nice thing about this class is 
(1) it expands to whatever types you like, and
(2) it prints nicely.

-Scott


-Scott






More information about the Python-list mailing list