I\'d like to create my own type of build-in namedtuple that has some extra features. Let\'s say we create a class:
from collections import namedtuple
MyClass
namedtuple
isn't a class, as you note; it's a function. But it's a function that returns a class. Thus, you can use the result of the namedtuple
call as a parent class.
Since it is immutable, a namedtuple
is initialized in __new__
rather in in __init__
.
So something like this, perhaps:
MyTuple = namedtuple('MyTuple', 'field1 field2')
class MyClass(MyTuple):
def __new__(cls, field1, field2):
if not isinstance(field1, int):
raise TypeError("field1 must be integer")
# accept int or float for field2 and convert int to float
if not isinstance(field1, (int, float)):
raise TypeError("field2 must be float")
return MyTuple.__new__(cls, field1, float(field2))