To_strin
__str__
To override to_string use def __str__(self):
Code for: __str__(self):
class MyCustomClass:
def __init__(self, value):
self.value = value
def __str__(self):
return f"MyCustomClass with value: {self.value}"
# Creating an instance of MyCustomClass
my_object = MyCustomClass(10)
# When we print the object, our custom __str__ method is used
print(my_object) # Output: MyCustomClass with value: 10
__repr__
However if you want the value to be to stringed from lists looks like __repr__
is the override, but be more careful with that.
GPT talk about __repr__ and List to string
The output you're seeing is a list of File
objects, but it's showing their memory addresses instead of the string representation defined in the __str__
method. This happens because when you print a list in Python, it uses the __repr__
method of the objects in the list, not the __str__
method.
To get the desired output, you can either:
-
Override the
__repr__
method in theFile
class, similar to how you did with__str__
. The__repr__
method is meant to return an "official" string representation of an object, and is used for debugging and other development purposes. It's generally a good practice to have__repr__
return a string that could be used to recreate the object, but in this case, you can make it similar to__str__
.class File: def __init__(self, file_path): self.file_path = file_path def __repr__(self): return f"{self.file_path}"
-
Or, manually print each
File
object in the list using a loop or a list comprehension, which will use the__str__
method:if __name__ == "__main__": files = list_files_recursively_in_dir("/tmp/dir1/", True) print([str(file) for file in files])
Either of these approaches will give you the string representation of each File
object in the list when printed.