[Python] If I subclass int, how to make arithmetic methods return the derived type?

Discussão em 'Python' iniciado por Stack, Novembro 26, 2025.

  1. Stack

    Stack Membro Participativo

    I want to construct objects which support arithmetic operations and have extra methods, e.g:

    class Timestamp(int):
    def as_seconds(self):
    return self / 90000


    The extra method works:

    >>> ts1 = Timestamp(135000)
    >>> ts1
    135000
    >>> ts1.as_seconds()
    1.5


    Arithmetic operations work, but they return instances of the base type instead of the derived type, so I cannot use the extra method anymore:

    >>> ts2 = ts1 + 22500
    >>> ts2
    157500
    >>> ts2.as_seconds()
    Traceback (most recent call last):
    File "<python-input-53>", line 1, in <module>
    ts2.as_seconds()
    ^^^^^^^^^^^^^^
    AttributeError: 'int' object has no attribute 'as_seconds'


    Is there a simple way to make that work without having to wrap all arithmetic methods? (i.e. __add__, __sub__, __mul__, etc...)

    Continue reading...

Compartilhe esta Página