I've run into certain code snippet which recreates some objects every time in the __str__
method of a class.
From what I recall, the __str__
method shouldn't bother with object creation. It should just do simple formatting operations and return a string.
But I do not have any evidence for such statement. Is there any convention or perhaps a PEP explaining proper __str__
usage? I've found only PEPs regarding str
vs. repr
usage.
I've searched Stack Overflow, but I haven't found an answer.
Edit:
You've asked for example. Unfortunately I can't share the snippet, because it isn't mine. I'm asking for general guidelines by the community (if such thing exists).
Here's a roughly similar usage:
from collections import OrderedDict
class A:
def __init__(self, a, b, c):
self.a = a
self.b = b
self.c = c
def __str__(self):
# recreated every time...
dict_sorted = OrderedDict(sorted(self.__dict__.items()))
result = []
for i in dict_sorted.keys():
result.append(str((i, dict_sorted[i])))
return ' '.join(result)
if __name__ == "__main__":
a = A('foo', 'bar', 'baz')
print(a)
It is totally okay, to create objects in the __str__
method. Python is a object oriented language, that creates objects all the time. In your example, a OrderedDict
, a list, a key-iterator, some tuples and strings are created. Would you also have doubts with this __str__
-method?
def __str__(self):
return ' '.join(str(item) for item in sorted(self.__dict__.items()))
It does exactly the same as your __str__
-method, but creates a few methods less. There are no restrictions to a __str__
-method, other than to return a string object. But the general advice for programmers holds true: a method shouldn't do something unexpected: so __str__
should create a string representation and nothing else.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.