How do I name different instances of the same object?

46 Views Asked by At

Im making a list of objects, where the list is of equal length to a list of file names. How can I make it so that each object is named after the corresponding name in the list of file names?

file_list = ['file1.txt','file2.txt','file3.txt'] 
object_list = []

for Object in file_list:

        object_list.append(Object(file1.txt))

Printing out object_list gives me something like:

[<__main__.Object object at 0x02C6D310>, <__main__.Object object at 0x02C6D330>, <__main__.Object object at 0x02C6D4B0>]

How do I make it so that it names each object to its file name so that I something along the lines of:

[File1, File2, File3]

Thanks

1

There are 1 best solutions below

1
On

While the comment by Loocid is perhaps a good way to do what you are doing, your exact question can also be answered. The way objects are transformed to text during this printing is handled by their __repr__() method. So you can define this method to display the file name, or whatever else you need. For example:

class Object:

    def __init__(self, fname):
        self._f = open(fname)
        self._fname = fname

    def __repr__(self):
        return self._fname

And then:

file_list = ['file1.txt','file2.txt','file3.txt'] 
object_list = []

for fname in file_list:
    object_list.append(Object(fname))

print(object_list)

which gives

[file1.txt, file2.txt, file3.txt]

Edit: I must note though that it is bad practice to use __repr__ like that. Ideally, it is supposed to return something that can be eval()ed back to the original object (or, at least, identifies it). So a good __repr__ would be

    def __repr__(self):
        return 'Object(' + self._fname + ')'