Using tuples correctly?

BJörn Lindqvist bjourne at gmail.com
Mon Oct 11 08:18:58 EDT 2004


> > So you could write stuff like this:
> >
> > return (r: 10, g: 20, b: 30) or maybe return (.r 10, .g 20, .b 30)
> 
> color = RGB(10, 20, 30)
> print "The red value is: ", color.red
> 
> If you *must* have a tuple to throw around, give your class a 'tuple' method:
> 
> class RGB(object):
>     def __init__(self, r=0, g=0, b=0):
>         self.red = r
>         self.green = g
>         self.blue = b
> 
>     def tuple(self):
>         return (self.r, self.g, self.b)
> 
> Why bother to shoehorn all of the name scaffolding into tuples when it's already present in classes?

Because you have to declare classes before you can instantiate them.
If you wanted a RGB tuple, would you really create a class for it? If
you wanted a 2d point? I guess tuples aren't really needed in python,
you can always get by by creating objects when you would have used
types. However, creating a class when all you want is a C-like struct
leads to alot of tedious and unnecessary work.

In my thinking, this:

return (r: 10, g: 20, b: 30)

would be read more as "create and return an anonymous object with
three attributes r, g, b set to 10, 20, 30". But maybe that solves a
problem that doesn't exist? Either people never use tuples and always
instantiate classes instead. OK. Fine. Or they use tuples because they
are convenient and becomes annoyed because they have to use index
access.
-- 
mvh Björn



More information about the Python-list mailing list