Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

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)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading