[Tutor] data structures in python?

Danny Yoo dyoo at hkn.eecs.berkeley.edu
Tue Nov 30 09:09:38 CET 2004



> void point_print (point p) {
>   printf("(%d, %d)\n", p.x, p.y);
> }


Hi Jeff,

Gah!  I forgot to rename that from point_print() to point_println():

/******/
void point_println(point p) {
   printf("(%d, %d)\n", p.x, p.y);
}
/******/

Sorry about that; I got sloppy when reworking the example to print out
something readable.  *grin*



Ideally, I would have rather made a function to return a string
representation of the point.  But correct, dynamic string manipulation in
standard C is a little ugly.  I guess I can make a broken example:

/******/
char* point_str(point p) {
  char *result;
  asprintf(&result, "(%d, %d)", p.x, p.y); /* I should be checking for
					      NULL here... */
  return result;
}

int main() {
  point p1 = point_make(3, 4);
  point p2 = point_make(7, 17);
  printf("%s\n", point_str(p1)); /* memory leak! */
  printf("%s\n", point_str(p2)); /* memory leak! */
  printf("%s\n", point_str(point_add(p1, p2))); /* memory leak! */
  return 0;
}
/******/

(To correct the C example, I should capture the result of point_str(), and
free() those memory blocks afterwards, but it clogs up the clarity of the
main() function.)


For the Python example, we write a similar "method" that emits a nice
string representation of a Point:

## Within the Point class definition ###
    def __str__(self):
        return "(%d, %d)" % (self.x, self.y)
###

The name we use here, __str__, is weird, but deliberately chosen.
Traditionally, we name a function that turns something in a string as
'__str__()', because Python has special hooks that automatically call it
in common situations.  For example, although we can call it directly:

###
>>> p = Point(42, 17)
>>> p.__str__()
'(42, 17)'
###


it's much nicer to use the str() builtin, which calls '__str__' for us:

###
>>> str(p)
'(42, 17)'
###

str() is the same function we used to get string values of numbers and
lists.  Now it works on our own data structures too!  (At least, as long
as we use "__str__" as the name of our string-making method.)


Best of all, the 'print' statement will automagically call str() on
anything it prints out:

###
>>> print p, "is my point"
(42, 17) is my point
###


Hope this helps!



More information about the Tutor mailing list