[Tutor] Array of structures

Daniel Yoo dyoo@hkn.eecs.berkeley.edu
Tue, 22 May 2001 19:42:25 -0700 (PDT)


On Tue, 22 May 2001, Glen Barnett wrote:

> Is there an equivalent Python script for the C language array of
> structures? An example C program is:
>=20
> struct day
> {
> =09char month[3];
> =09int day;
> =09int year;
> };

Almost.  Python's list structures can hold arbitrary elements:

###
>>> mylist =3D [1, "two", "iii", 4]
>>> mylist
[1, 'two', 'iii', 4]
###

which will also allows us to store Dates into a list.  If we want to
presize a list, we can fill it up with a bunch of zeros:

###
birthdays =3D [0] * 15     ## Let's make 15 birthdays
###

and then initialize each list element appropriately.  What's nice is that
Python's lists can grow: we can append() new elements to them:

###
>>> names =3D ['glen']
>>> names.append('danny')
>>> names
['glen', 'danny']
###

so you don't need to worry so much about sizing Python lists: they'll
expand for you.


When we're doing structures in Python, we can either bundle the whole
thing together as a list:

###
def MakeDate(month, day, year):
    return [month, day, year]

def GetMonth(date):  return date[0]
def GetDay(date): return date[1]
def GetYear(date): return date[2]
###


or as a dictionary:

###
def MakeDate(month, day, year):
    return { 'month' : month,
             'day' : day,
             'year' : year }

def GetMonth(date): return date['month']
def GetDay(date): return date['day']
def GetYear(date): return date['year']
###


(I'm renaming your struct Day as a "Date" --- I thought that the name was
a little confusing.)  Above, we're using a small helper function to help
construct these dates for us; more formally, we're making our own
"constructor" for dates.  We also have a few helper functions to help us
grab parts out of our date.


If we have either of the above date implementations, we can write
PrintIt() from the C version:

> void PrintIt( struct day bd )
> {
> =09printf (=93\nMonth %c%c%c  =94, bd.month[0], bd.month[1] bd.month[2]);
> =09printf (=93Day %d  =94, bd.day );
> =09printf (=93Year %d=94, bd.year);
> }

to a Python version like this:

###
def PrintIt(date):
    print "Month: %s\nDay %d\nYear %d" % (GetMonth(date),
                                          GetDay(date),
                                          GetYear(date))
if __name__ =3D=3D '__main__':
    birthday =3D MakeDate("Jan", 21, 1970)
    PrintIt(birthday)
###


Another implementation that's a little closer to your defintion uses a
class approach:

###
class Date:
    def __init__(self, month, day, year):
        self.month =3D month
        self.day =3D day
        self.year =3D year
###

and when you get to object oriented programming, I think you will have a
blast with it.  *grin*  Good luck!