Newbie Question: Giving names to Elements of List/Tuple/Dict
Alfredo P. Ricafort
alpot at mylinuxsite.com
Fri Nov 29 10:10:16 EST 2002
Hi Paul,
Thanks. I think your suggestion comes close to what I am looking for
i.e. an array of objects rather than an array of strings (which is what
I original had in mind).
AL
On Fri, 2002-11-29 at 20:41, Paul Simmonds wrote:
> >I'm quite new to Python. So far I find it to be easy to learn and
> >simple to program. However, one thing that I missed, especially someone
> >coming from C language, is 'struct'. It seems that when you define a
> >data structure in the form of a List, Tuple, or Dict., there is no way
> >to give names to each element.
> >
> >For example:
> >
> >In C:
> > struct Customer {
> > char * Name;
> > char * Address;
> > char * TelNo;
> > } Customer[];
> >
> > printf("Customer Name is %s\n",Customer[i].Name);
> >
> >
> >In Python:
> > Customer=[ [Name,Addres,TelNo], [Name,Address,TelNo],.....]
> >
> > print "Customer Name is %" Customer[i][0]
> >
> Hmmm. I'm dealing with that sort of thing at the moment, and I find that
> Python classes come in really useful. Try:
>
> class Customer(object):
> """Default Customer Definition"""
> def __init__(self):
> self.name=""
> self.address=""
> self.telno=""
>
> This is so much more flexible than the C structure. For example:
>
> >>>from randomobj import *
> >>>custlist=[Customer(),Customer()]
>
> Gives you 2 Customer class instances, each with its own set of variables as
> you defined above(not strictly correct, but good enough for simple
> explanation):
>
> >>>custlist.append(Customer()) # Add another customer
> >>>print custlist # Actually a list of 'pointers'
> [<randomobj.Customer object at 0x81545ec>, <randomobj.Customer object at
> 0x811ebcc>, <randomobj.Customer object at 0x8155a04>]
> >>>print custlist[0].__dict__ # Access all attributes
> {'telno': '', 'name': '', 'address': ''}
> >>>custlist[0].name='Paul Simmonds' # Accessing by name
> >>>custlist[0].telno='123456'
> >>>print custlist[0].__dict__ # Changed attributes
> {'telno': '123456', 'name': 'Paul Simmonds', 'address': ''}
>
> This form will probably do as much as you want, but you can include more
> functionality by wrapping the 'object' special functions. However, the
> Python.org Reference Manual section 3.3 explains it better than I can.
>
> HTH,
> Paul
>
> <snip>
> >Thanks.
> >
> >AL
> >
> >--
> >http://mail.python.org/mailman/listinfo/python-list
>
>
> _________________________________________________________________
> Add photos to your e-mail with MSN 8. Get 2 months FREE*.
> http://join.msn.com/?page=features/featuredemail
--
Alfredo P. Ricafort <alpot at mylinuxsite.com>
Home
More information about the Python-list
mailing list