0

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>]
martineau
  • 119,623
  • 25
  • 170
  • 301
Alex
  • 599
  • 1
  • 5
  • 14
  • Have you tried overriding the `__str__()` method of the `Case` class? – szamani20 Feb 24 '20 at 01:32
  • 2
    Most objects in Python don't have any concept of a name. Why do you want your objects to have names? – user2357112 Feb 24 '20 at 01:32
  • @user2357112supportsMonica It is usefull when I'm exploring the object. I want to see names cause they correspond to folders – Alex Feb 24 '20 at 01:33
  • 1
    If you want to see the folders, you can overload `Case.__repr__` so `Case('blah')` displays as `Case('blah')` instead of the default, but I would recommend against thinking of this as an object's name. – user2357112 Feb 24 '20 at 01:35

1 Answers1

1

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
John Kugelman
  • 349,597
  • 67
  • 533
  • 578
venkata krishnan
  • 1,961
  • 1
  • 13
  • 20