Home > Software design >  Python3 inheritance from collections.namedtuple: TypeError: object.__init__() takes exactly one argu
Python3 inheritance from collections.namedtuple: TypeError: object.__init__() takes exactly one argu

Time:09-22

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:\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.

CodePudding user response:

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.

  • Related