gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 00:40:54 24 4
gpt4 key购买 nike

我希望能够从另一个模块获取命名元组的 _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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com