create custom namedtuple type with extra features

后端 未结 2 1243
死守一世寂寞
死守一世寂寞 2021-01-18 16:19

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         


        
2条回答
  •  天涯浪人
    2021-01-18 17:04

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

提交回复
热议问题