On 11/1/14 12:56 PM, duncan smith wrote:
Hello,
       I have a Bloom filter class and want to (partially) serialize
instances using hex() or oct(). Instances are mutable, so I can't
inherit from long. I thought I'd found the answer when I came across
__index__,
https://docs.python.org/2/reference/datamodel.html#object.__index__. But
it doesn't seem to work as I expected it to.


class MyClass(object):
        def __init__(self):
                self.val = 7
        def __index__(self):
                return self.val

        
x = MyClass()
oct(x)

Traceback (most recent call last):
   File "<pyshell#76>", line 1, in <module>
     oct(x)
TypeError: oct() argument can't be converted to oct
oct(x.__index__())
'07'



Can someone please explain why my thinking is wrong on this? TIA.

Just above your link in the docs is __oct__ and __hex__, which are used to implement oct() and hex(): https://docs.python.org/2/reference/datamodel.html#object.__oct__

That said, I would simply add a .hex() method on the class. I would never expect a complex thing like a Bloom filter to be turned into useful hex with the hex() builtin.

For example, when making an MD5 hash, you use the md5.hexdigest() method, not hex(md5).

--
Ned Batchelder, http://nedbatchelder.com

--
https://mail.python.org/mailman/listinfo/python-list

Reply via email to