Python命名约定namedtuples

2024-04-29 03:38:38 发布

您现在位置:Python中文网/ 问答频道 /正文

我是Python新手,我一直在阅读在线文档,并(尝试)遵循PEP 0008来获得一个好的Python代码风格。 我对在研究re库时在官方Pythondocs中发现的代码段很好奇:

import collections

Token = collections.namedtuple('Token', ['typ', 'value', 'line', 'column'])

我不明白为什么Token变量以大写的第一个字母命名;我通读了pep0008,但我所看到的没有引用它。它应该不是token而是TOKEN如果它是一个常量(我知道它不是这样的)?在


Tags: 代码文档importretoken官方value风格
2条回答

在您提供的代码段中,Tokennamed tuple,绝对不是常量。它不遵循其他变量名命名样式,只是为了强调它是一个类工厂函数。 如果将pep0008样式检查器写成token,则不会从pep0008样式检查器发出警告(例如PyCharm),但我认为这不是一个好的实践,因为这种方式无法将它区分为类工厂名称。在

因此,namedtuples属于pep0008中的Class names。太糟糕了没有更明确地说明。 除了您提到的writing a tokenizer示例外,还可以在collections.namedtuple docs示例中看到:

Point = namedtuple('Point', ['x', 'y'])
Point3D = namedtuple('Point3D', Point._fields + ('z',))
Book = namedtuple('Book', ['id', 'title', 'authors'])

这里的键是^{}。文件上说

collections.namedtuple(typename, field_names, verbose=False, rename=False)

Returns a new tuplesubclass named typename. The new subclass is used to create tuple-like objects that have fields accessible by attribute lookup as well as being indexable and iterable. Instances of the subclass also have a helpful docstring (with typename and field_names) and a helpful __repr__() method which lists the tuple contents in a name=value format.

没有pep8冲突;Token是一个用户定义的类,它的名称应该大写。在

相关问题 更多 >