Inherit class Decimal, and add another input argument in the constructor

Question:

A minimal example to reproduce my problem:

from decimal import Decimal

class MyDecimal(Decimal):
    def __init__(self, value, dummy):
        super().__init__(value)
        print(dummy)

x = MyDecimal(5, 'test')

Throws:

TypeError: optional argument must be a context

A similar issue is described in this question, but the answer suggests that this is a bug which was fixed on Python 3.3, and I’m using Python 3.9.

Any idea what I’m doing wrong here, or how else I can inherit class Decimal while using a different constructor prototype in my class (i.e., additional input arguments before and after the input argument passed to the base class upon construction)?

Asked By: bbbbbbbbb

||

Answers:

decimal.Decimal uses __new__ instead of __init__, because Decimal instances are immutable, and initializing in __init__ would be a mutative operation. You need to implement __new__ yourself:

import decimal

class MyDecimal(decimal.Decimal):
    def __new__(cls, value, dummy):
        print(dummy)
        return super().__new__(cls, value)
Answered By: user2357112
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.