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
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:And then:
which gives
Edit: I must note though that it is bad practice to use
__repr__
like that. Ideally, it is supposed to return something that can beeval()
ed back to the original object (or, at least, identifies it). So a good__repr__
would be