Alex
Alex

Reputation: 636

How to give names to class instances instantiated with "for" loops?

As an attribute to a certain class, I'm instantiating a bunch of objects of another class. My problem is that they have ugly names for memory addresses. How do I give them proper names?

class CaseReader(object):
    def __init__(self, path):
        cases_paths = glob(path + '//*')
        cases_names = os.listdir(path)
        self.case = [Case(i) for i in cases_paths]

Upon running:

a = CaseReader(path)
a
Out[4]: <__main__.CaseReader at 0x1c6dfc7fa88>
a.case
Out[5]: 
[<__main__.Case at 0x1c6dfc99fc8>,
 <__main__.Case at 0x1c6dfc99dc8>,
 <__main__.Case at 0x1c6dfcaf3c8>,
 <__main__.Case at 0x1c6dfcaf448>,
 <__main__.Case at 0x1c6dfcaf208>]

Upvotes: 0

Views: 64

Answers (1)

venkata krishnan
venkata krishnan

Reputation: 2046

Overwrite the __str__ function in the class definition and print what ever attributes you want to see, when you print the reference of the object.

Sample Code

class A:
    def __init__(self, name):
         self.name = name
    def __str__(self):
         return self.name

Upvotes: 1

Related Questions