inheritance, types, operator overload, head ache

thorley at gmail.com thorley at gmail.com
Mon Jul 10 10:14:23 EDT 2006


Thanks very much for the reply. I'll give that a shot and post back
with the result.

--
matthew

Bruno Desthuilliers wrote:
> thorley at gmail.com a écrit :
> > I'm working with the following code. I included some tests to make it
> > easy to see--if you run the code--what troubles I'm having.
> >
> > 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)
>
> and it did the trick for printing. Now it may have other side-effects, I
> don't know.
>
> > and why obj.__int__() works, but not int(obj).
>\
> I've added tracing to  __int__, and it isn't called. FWIW, str type has
> no attribute __int__, so I guess there's something special in the
> implementation here.
>
> > I just don't get it. :(
>
> FWIW, you have another problem to solve:
>
> >>> b1 = Byte(1)
> >>> b1
> '\x01'
> >>> b1.__int__()
> 1
> >>> b2 = Byte(2)
> >>> b2
> '\x02'
> >>> b2.__int__()
> 2
>  >>> b1.__int__()
> 2
>
> cf below...
>
> (snip)
> >
> > <code>
> > import struct
> > class Byte(str): # Implement Bytes as str for easy adding and joining
> (snip)
> >     def __new__(self, val):
>
> Actually, __new__ is a static method, and it takes the class as first
> argument. So...
>
> >         if type(val) == str and not val.isdigit():
> >             val = struct.unpack('B', val) #ensure input is valid struct
> > byte
> >         self._byte = struct.pack('B', val)
> >         self._int = int(val)
>
> .. since the name "self" really references the class, not the instance,
> the two previous lines (re)bind *class* attributes "_byte" and "_int" to
> class Byte.
>
> >         return str.__new__(self, self._byte)
>
> 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
> 
> (snip)




More information about the Python-list mailing list