PEP 8 prescribes那个
Constants are usually defined on a module level and written in all capital letters with underscores separating words. Examples include
MAX_OVERFLOW
andTOTAL
.
我知道这只是一个命名约定,但我很想知道是否有官方或广泛接受的定义来说明常量与半私有(private)变量的实际构成。
这是否仅限于您所说的 mathematical constants ? (即float、int、complex)
或者它会包含诸如 datetime.date
对象或在模块级别定义的字符串之类的东西吗?具有混合类型的键/值的字典怎么样?如果答案是否定的,是否应该将这些类型的对象定义为带有 _leading_underscore
的(准)私有(private)变量?
最佳答案
嗯,PEP 8编码约定主要是Python 标准库编写的:
This document gives coding conventions for the Python code comprising the standard library in the main Python distribution.
通过搜索 Python 3.5 标准库中的一些模块,以及常见的字符串和数字,可以找到像
UUID
s, uuid.py:
NAMESPACE_URL = UUID('6ba7b811-9dad-11d1-80b4-00c04fd430c8')
正则表达式,smtplib.py
OLDSTYLE_AUTH = re.compile(r"auth=(.*)", re.I)
字典,pliSTLib.py:
_BINARY_FORMAT = {1: 'B', 2: 'H', 4: 'L', 8: 'Q'}
frozenset
s, asyncore.py:
_DISCONNECTED = frozenset({ECONNRESET, ENOTCONN, ESHUTDOWN, ECONNABORTED, EPIPE, ...
和 calendar.py 中的datetime.date
_EPOCH_ORD = datetime.date(EPOCH, 1, 1).toordinal()
因此基本上任何应该在整个执行期间保持不变的东西,即使它是可变类型(pliSTLib.py 中的字典)也是如此。
关于python - 什么是 Python 中的常量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46004474/