[Python] Is it possible to redefine or create a new dunder method to built in objects like...

Discussão em 'Python' iniciado por Stack, Dezembro 8, 2024.

  1. Stack

    Stack Membro Participativo

    I’m trying to define a new type of division such that 1/0 doesn’t raise a ZeroDivisionError, instead, it returns a new object called infty(0), which is defined as follow:

    class infty:

    def __init__(self, sign:int):
    if sign > 0:
    self.sign = 1
    elif sign < 0:
    self.sign = -1
    else:
    self.sign = 0

    def __repr__(self):
    if self.sign > 0:
    return '∞'
    if self.sign < 0:
    return '-∞'
    return '?'


    so I have made a new function:

    def safediv(a:int, b:int) -> float|infty:
    if b == 0:
    return infty(0)
    return a/b


    and tried to assign it to truediv by int.__truediv__ = safediv

    but it fails with the error message:

    int.__truediv__ = safediv
    ^^^^^^^^^^^^^^^
    TypeError: cannot set '__truediv__' attribute of immutable type 'int'


    Is there a way to achieve the effect that 1/0 returns infty(0)?

    Continue reading...

Compartilhe esta Página