Mike Krell wrote: >> class S(str): >> def __str__(self): return "S.__str__" >> >> class U(unicode): >> def __str__(self): return "U.__str__" >> >> print str(S()) >> print str(U()) >> >> This script prints: >> >> S.__str__ >> U.__str__ > > Yes, but "print U()" prints nothing, and the explicit str() should not > be necessary. The main difference here is that the string object defines a tp_print slot, while Unicode doesn't. As a result, tp_print for the string subtype is called and this does an extra check for subtypes: if (! PyString_CheckExact(op)) { int ret; /* A str subclass may have its own __str__ method. */ op = (PyStringObject *) PyObject_Str((PyObject *)op); if (op == NULL) return -1; ret = string_print(op, fp, flags); Py_DECREF(op); return ret; } For Unicode, the PyObject_Print() API defaults to using PyObject_Str() which uses the tp_str slot. This maps directly to a Unicode API that works on the internals and doesn't apply any extra checks to see if it was called on a subtype. Note that this is true for many of the __special__ slot methods you can implement on subtypes of built-in types - they don't always work as you might expect. Now in this rather common case, I guess we could add support to the Unicode object to do extra checks like the string object does. Dito for the %-formatting. -- Marc-Andre Lemburg eGenix.com Professional Python Services directly from the Source (#1, Oct 25 2006) >>> Python/Zope Consulting and Support ... http://www.egenix.com/ >>> mxODBC.Zope.Database.Adapter ... http://zope.egenix.com/ >>> mxODBC, mxDateTime, mxTextTools ... http://python.egenix.com/ ________________________________________________________________________ ::: Try mxODBC.Zope.DA for Windows,Linux,Solaris,FreeBSD for free ! ::::
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4