Python does not have a lot of semantic type restrictions for the given functions and methods, but it has several, and here is one of them: __str__ (in Python 2. *) should return a byte string. As usual, if a Unicode object is found where a byte string is required, the current default encoding (usually 'ascii' ) is applied when trying to make the desired byte string from a Unicode object.
For this operation, the encoding (if any) of any given file object does not matter, because what is returned from __str__ can be printed, or it can undergo a completely different and unrelated treatment. Your goal when calling __str__ does not matter for the call itself and its results; Python, in general, does not take into account the "future context" of the operation (what you intend to do with the result after the operation is completed) when defining the semantics of the operation.
This is because Python does not always know your future intentions and is trying to minimize the number of surprises. print str(x) and s = str(x); print s s = str(x); print s (the same operations performed in one gulp versus two), in particular, should have the same effects; if in the second case there will be an exception if str(x) cannot correctly create a string of bytes (that is, for example, x.__str__() cannot), and therefore the exception should also occur in another case.
print itself (starting from 2.4, I suppose), when representing a Unicode object, takes into account the .encoding attribute (if any) of the target stream (by default sys.stdout ); other operations not yet associated with any given target stream are not - and str(x) (i.e. x.__str__() ) is such an operation.
I hope this helped show the reason for the behavior that annoys you ...
Edit : OP now clarifies: "My main problem is to make the class" printable ", that is, print A () prints something completely readable (not with Unicode characters \ x ***).". Here's the approach that I think is best suited for this particular purpose:
import sys DEFAULT_ENCODING = 'UTF-8'
That is, this approach focuses on __unicode__ as the main way for class instances to format them, but since (in Python 2) print calls __str__ instead, it has this delegate for __unicode__ with the best that it can do in terms of encoding. Not perfect, but then the Python 2 print statement is far from perfect, -).
__repr__ , for its part, should strive to be unambiguous , that is, not to “look beautiful” due to the risk of ambiguity (ideally, when possible, it should return a byte string that, if passed to eval , will make the instance equal to the present ... which is far from always possible, but the lack of ambiguity is the absolute core of the difference between __str__ and __repr__ , and I strongly recommend that this difference be respected!).