python - 从其他模块访问 python nametuple _fields

标签 python namedtuple

我希望能够从另一个模块获取命名元组的 _fields 成员的长度。但是,它被标记为 protected 。

我的解决方法如下:

MyTuple = namedtuple(
    'MyTuple', 
    'a b'
)
"""MyTuple description

Attributes:
    a (float): A descrip
    b (float): B descrip
"""
NUM_MY_TUPLE_FIELDS = len(MyTuple._fields)

然后我从外部模块导入 NUM_MY_TUPLE_FIELDS。

我试图找到一种方法使功能成为类的一部分,例如使用 __len__ 方法扩展namedtuple。有没有一种更Pythonic的方法来从外部模块获取namedtuple中的字段数量?

已更新以显示自动文档注释。在 PyCharm 中可以看到 protected 警告。最初,在外部模块中我只是简单地导入了MyTuple,然后使用:

x = len(MyTuple._fields)

我尝试了以下建议并认为它会起作用,但我得到以下信息:TypeError: object of type 'type' has no len().

class MyTuple(typing.MyTuple):
    a: float
    b: float
    """MyTuple doc

    Attributes:
        a (float): A doc
        b (float): B doc
    """
    def __len__(self) -> int:
        return len(self._fields)

fmt_str = f"<L {len(MyTuple)}f"   # for struct.pack usage
print(fmt_str)

最佳答案

您可以使用继承:

class MyTuple(namedtuple('MyTuple', 'a b c d e f')): 
    """MyTuple description

    Attributes:
       a (float): A description 
       ...
    """
    @property
    def fields(self): 
        # _fields is a class level attribute and available via
        # MyTuple._fields from external modules
        return self._fields

    def __len__(self): 
        # your implementation if you need it
        return len(self._fields)

或使用typing.NamedTuple如果您使用的是 python 3.5+

class MyTuple(typing.NamedTuple): 
   a: int
   # other fields 

关于python - 从其他模块访问 python nametuple _fields,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57360905/

相关文章:

python - django 并执行一个单独的 .py 来操作数据库

python - Pandas - Dataframe 有带列表的列。如何对列表中的元素进行分组?

python - 如何为 python NamedTuple 实现 "varying"默认参数

python - NamedTuple 声明并在一行中使用

python - 从命名元组基类继承

python - 在 matplotlib 中使用绘图、轴或图形绘制绘图有什么区别?

python - Flask 邮件安全不符合 Microsoft Outlook 的安全要求?

python /usr/bin/env : bad interpreter: Not a directory

python - 如何将 Pandas 数据框转换为命名元组

python - 为什么 namedtuple._as_dict() 比使用 dict() 转换慢