[Tutor] printing value returning from a Class

Kalle Svensson kalle.svensson at gmail.com
Thu Sep 13 15:11:44 CEST 2007


Hello!

On 9/13/07, Varsha Purohit <varsha.purohit at gmail.com> wrote:
> Hello friends,,
>           I have a problem in displaying data  which i have invoked from
> class. City is the name of the class which i havent displayed here. There is
> another script using that class. It has a function name setCities which
> takes a text file as argument. Text file contains name of the city, x and y
> location. there are 4 datas in 4 different lines. Code is as follows.
>
> import City
>
> def setCities(inFile):
>     # puts city.txt content into City class objects
>     # the field order of input file is: name x y   x, y are integers. data
> are in newlines.
>     f = open(inFile, 'r')
>     body = f.readlines()
>     f.close()
>     cities = []  # list of cities
>     for row in body:
>         cityData = row.strip().split()
>         cityName = cityData[0]
>         cityX = cityData[1]
>         cityY = cityData[2]
>         newCity = City(cityName, cityX, cityY)  # city class is invoked
>         cities.append(newCity)
>     return cities
>
>
> abc = setCities("C:\MS\sem5\Lab2_scripts\cities.txt")  #
> setCities function will return the array with values read from the file.
> print abc
>
> I am getting output like
> [<city.City instance at 0x023E82D8>, <city.City instance at 0x023E8300>,
> <city.City instance at 0x023E8350>, <city.City instance at 0x023E83C8>]
>
> I want the data and not the instance... what should i do ??

Well, that depends on the City class. When you print a list, it just
calls repr() on each item in the list and prints that. Now, suppose
there is a method printCity() in the City class for printing the city
data. In that case you should probably just loop over the list of
instances and call the method, like this:

>>> abc = setCities("city file")
>>> for city in abc:
...     city.printCity()

If there is no such method, maybe you can extract the data from the
class and write your own printing function, or modify the class to add
one.

HTH,
  Kalle


More information about the Tutor mailing list