是否应该仍然在模块级别声明

是否应该仍然在模块级别声明

本文介绍了特定于类的“常量"是否应该仍然在模块级别声明?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

PEP 8 中,声明常量通常定义在模块级别 [...]".这对于标准库来说是有意义的,其中常量往往属于整个模块而不是特定类(例如 zlib.MAX_WBITSre.UNICODE).但是,我目前正在编写一个模块,其中的常量都与各个类相关.

In PEP 8, it's stated that "Constants are usually defined on a module level […]". This makes sense for the standard library, where constants tend to pertain to the entire module rather than a particular class (e.g. zlib.MAX_WBITS or re.UNICODE). I'm currently writing a module, however, where the constants are all related to individual classes.

该模块旨在允许 Python 程序使用特定于应用程序的序列化格式,在该格式中,数据块被排列成块",而这些块又被进一步排列成区域".块和区域的维度是公开的有用常量,我一直将其作为类属性这样做,直到我在 PEP 8 中偶然发现了这一行.

The module is designed to allow Python programs to work with an application-specific serialization format in which blocks of data are arranged into "chunks" and those chunks are further arranged into "regions". The dimensions of chunks and regions are useful constants to expose, and I had been doing so as class properties until I chanced across that line in PEP 8.

我倾向于保持原样(PEP 8 说愚蠢的一致性毕竟是小人的妖精"),但我想确保我不会这样做会严重破坏用户的期望.(该模块尚未发布,因此向后兼容性不是问题.)

I'm inclined to leave them as they are (PEP 8 also says "foolish consistency is the hobgoblin of little minds", after all), but want to make sure that I won't be too badly breaking users' expectations by doing so. (The module hasn't yet been released, so backwards compatibility isn't an issue.)

作为参考,PEP 8"风格......

For reference, "PEP 8" style…

CHUNK_SIZE_X = 16
CHUNK_SIZE_Z = 16
REGION_SIZE_X = 32
REGION_SIZE_Z = 32

def Chunk(object):
    # magic happens here

def Region(object):
    # magic happens here

……以及我目前的基于类"的风格……

…and my current, "class-based" style…

def Chunk(object):
    SIZE_X = 16
    SIZE_Z = 16

    # magic happens here

def Region(object):
    SIZE_X = 32
    SIZE_Z = 32

    # magic happens here

推荐答案

显然,基于类的常量属于类.坚持你的第二个例子.请记住,PEP8 不是从全能者传下来的.只是好主意:传统、理性和经验可以调和圣经的含义.

Clearly, class-based constants belong in the class. Stick with your second example. Remember PEP8 is not handed down from the Almighty. It's just good ideas: tradition, reason and experience can temper the meaning of scripture.

Hungrarian_prefix_notation 是不必要的.这是您上课的原因之一.

Hungrarian_prefix_notation is needless. That's one reason you have classes.

这篇关于特定于类的“常量"是否应该仍然在模块级别声明?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-30 03:22