« Pictures you can use - for free - from our library | Main | Downloading data for use in Excel (from PHP / MySQL) »
January 24, 2008
Python - formatting objects
If you're going to be printing out objects from within Python, simply provide an __str__ method in the class and it will do all the work for you. Indeed - why not create classes and objects for straightforward objects such as people's names ... then you can call up the formatter for them very easily and have it defined just once in your code.
class person:
def __init__(this,name):
this.name=name
def __str__(this):
return "%-12s" % this.name
people = ["John","George","Paul","Esmerelda","Jo","Petal"]
plist = []
for current in people:
plist.append(person(current))
for j in range(len(plist)):
print plist[j],j
running that:
Dorothy:py08 grahamellis$ python names
John 0
George 1
Paul 2
Esmerelda 3
Jo 4
Petal 5
Dorothy:py08 grahamellis$
Posted by gje at January 24, 2008 05:26 PM