inheritance, types, operator overload, head ache

Georg Brandl g.brandl-nospam at gmx.net
Tue Jul 11 16:12:16 EDT 2006


thorley at gmail.com wrote:
>> > > Can some one *please* splain me why str(obj) works but not print obj,
>> >
>> > May have something to do with escape chars... I tried with:
>> >    def __str__(self):
>> >       return repr(self)
> 
> Yes, that appears to be correct. Experiments indicated that it's an
> issue with escaping.
> 
> 
>> > What you want here is to first create the instance, and only then bind
>> > to it:
>> >
>> >      def __new__(cls, val):
>> >          if type(val) == str and not val.isdigit():
>> >              val = struct.unpack('B', val)
>> >          _byte = struct.pack('B', val)
>> >          self = str.__new__(cls, _byte)
>> >          self._byte = _byte
>> >          self._int = int(val)
>> >          return self
> 
> Oh, I see. I tried that and it worked well, but the broken int(obj) is
> too annoying.

The problem is that int() checks if the argument is a string (which includes
subclasses) and directly tries to convert the string without looking at
__int__. If you want, you can report this as a bug and see if other
developers agree.

Georg



More information about the Python-list mailing list