Main Content

Python - formatting objects

Archive - Originally posted on "The Horse's Mouth" - 2008-01-24 17:26:34 - Graham Ellis

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$