[Tutor] data structures in python?

Danny Yoo dyoo at hkn.eecs.berkeley.edu
Tue Nov 30 08:43:39 CET 2004

On Mon, 29 Nov 2004, Jeff Peery wrote:

>  is there something similar in python to a data structure in C? Would
> this be like creating a new module, or a new object?

[meta: includes C and Python code for comparison purposes]

Hi Jeff,

Sort of.  Class definitions can play the role of structures.

For example, let's say that we were doing some 2d graphs, and would like
to represent things as (x, y) coordinate points.  In C, we can write a
point definition and a small program to add points together:

/*** C code ***/
#include <stdio.h>
typedef struct {
  int x;
  int y;
} point;

point point_make(int x, int y) {
  point p;
  p.x = x;
  p.y = y;
  return p;

point point_add (point p1, point p2) {
  return point_make(p1.x + p2.x, p1.y + p2.y);

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

int main() {
  point p1 = point_make(3, 4);
  point p2 = point_make(7, 17);
  point_println(point_add(p1, p2));
  return 0;

Here, we've defined a structure 'point' and a few functions to play
specifically with those points.  If we want to do a strict "Abstract Data
Type" (ADT) approach, we would only allow access to the structure through
those functions alone, and forbid clients from touch the inner structure
of a point at all.

Now we can do a similar thing in Python, by using classes:

import sys

class Point:
    def __init__(self, x, y):
        self.x, self.y = x, y

    def add(self, other):
        return Point(self.x + other.x, self.y + other.y)

    def println(self):
        print "(%d, %d)" % (self.x, self.y)

if __name__ == '__main__':
    p1 = Point(3, 4)
    p2 = Point(7, 17)

Here, the code tries to make it more clear that the helper functions "add"
and "println" really belong to Points, so that's why they're nested within
the Point definition.

It's not exactly a one-to-one mapping between the C point and Python Point
code, but it's somewhat close.

Note that there's no explicit definition of the real "structure" of a
point in the Python translation.  This might be unsettling: we really
depend on our initializer to do proper initialization of a Point, so this
is actually quite a bit less rigid than a real C structure.

Just as C's make_point() guarantees that its return value is properly
initialized, the Point's __init__ guarantees the same kind of
initialization.  So in practice, this turns out to work pretty well.

I hope this makes the point clearer.  *grin*  Good luck!

More information about the Tutor mailing list