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

Question:

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:

Traceback (most recent call last):
  File "D:Sync1CodePython3EconoPyVersion_0.2test.py", line 22, in <module>
    print(TransactionClass(1,1,1,1,1))
  File "D:Sync1CodePython3EconoPyVersion_0.2test.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.

Asked By: Abel Gutiérrez

||

Answers:

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.

Answered By: saquintes
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.