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

Time:08-31

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)?

CodePudding user response:

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)
  • Related