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

Python3 inheritance from collections.namedtuple: TypeError: object.__init__() takes exactly one argument (the instance to initialize)

I want to create a child class of collections.namedtuple

This is my code:

from collections import namedtuple

TransactionTuple = namedtuple(
    typename="Transactionttt",
    field_names=[
        "transactionDate",
        "valueDate",
        "value",
        "currency",
        "concept"
    ],
    defaults=("",)
)


class TransactionClass(TransactionTuple):
    
    def __init__(self, transactionDate, valueDate, value, currency, concept):
        
        super().__init__(transactionDate, valueDate, value, currency, concept)

print(TransactionClass(1,1,1,1,1))

And this is the output:

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

Traceback (most recent call last):
  File "D:\Sync1\Code\Python3\EconoPy\Version_0.2\test.py", line 22, in <module>
    print(TransactionClass(1,1,1,1,1))
  File "D:\Sync1\Code\Python3\EconoPy\Version_0.2\test.py", line 20, in __init__
    super().__init__(transactionDate, valueDate, value, currency, concept)
TypeError: object.__init__() takes exactly one argument (the instance to initialize)

I think that the problem is related to super().__init__(), but I don’t find a solution.

>Solution :

from collections import namedtuple

TransactionTuple = namedtuple(
    typename="Transactionttt",
    field_names=[
        "transactionDate",
        "valueDate",
        "value",
        "currency",
        "concept"
    ],
    defaults=("",)
)


class TransactionClass(TransactionTuple):

    def __init__(self, transactionDate, valueDate, value, currency, concept):
        super().__init__()

print(TransactionTuple(1, 1, 1, 1, 1))
print(TransactionClass(1, 1, 1, 1, 1))

produces

Transactionttt(transactionDate=1, valueDate=1, value=1, currency=1, concept=1)
TransactionClass(transactionDate=1, valueDate=1, value=1, currency=1, concept=1)

My guess is that the class from namedtuple populates its instance through the __new__ function, and so doesn’t actually take anything into its __init__() (just a guess). So if you have other things, you should be able to add them to the __init__() you have, or if that’s it, then you can just remove it.

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