[Python] How can I control conversion from custom object to numpy.longdouble?

Discussão em 'Python' iniciado por Stack, Abril 3, 2025.

  1. Stack

    Stack Membro Participativo

    I have a custom class that (for historical reasons) stores high-precision numbers as two integers representing the integer part and the nano-precision non-integer part, e.g.:

    class Custom(object):
    def __init__(self, int_, nano_):
    self._int = int_
    self._nano = nano_

    def __float__(self):
    return self._int + self._nano * 1e-9

    def __int__(self):
    return self._int


    However, when I try to convert this to numpy.longdouble it's going through the __float__ method:

    >>> a = Custom(1234567890, 123456789)
    >>> print(numpy.longdouble(a))
    1234567890.1234567165
    >>> print(numpy.longdouble(float(a)))
    1234567890.1234567165
    >>> print(numpy.longdouble(a._int) + numpy.longdouble(a._nano * 1e-9))
    1234567890.123456789


    The final example there is the result I want. So the question is, how can I override the default behaviour of casting to numpy.longdouble?

    Continue reading...

Compartilhe esta Página