Newbie Question: Giving names to Elements of List/Tuple/Dict
Paul Simmonds
psimmo60 at hotmail.com
Fri Nov 29 07:41:19 EST 2002
>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
More information about the Python-list
mailing list