根据 PEP8 的常量 class 属性样式:大写还是小写?

Constant class attribute style according to PEP8: uppercase or lowercase?

我真的很喜欢遵循标准编码风格,但找不到答案。

class Card:
    """Card class representing a playing card."""
    RANKS = (None, 'Ace', '2', '3', '4', '5', '6', '7', '8', '9', '10',
             'Jack', 'Queen', 'King')
    SUITS = ('Clubs', 'Spades', 'Diamonds', 'Hearts')

    def __init__(self, rank, suit):
        self.rank = rank
        self.suit = suit

    def __str__(self):
        return f"{Card.RANKS[self.rank]} of {Card.SUITS[self.suit]}"


c = Card(1, 1)
print(c)

我应该在class属性中写常量all_lower_case还是ALL_UPPER_CASE? PEP8 只是说常量在模块级别应该是 ALL_UPPER_CASE。 classes 呢?

为什么不像这样提取模块中 class 之外的那些:

from enum import Enum

class Suit(Enum):
    CLUBS = 1
    SPADES = 2
    DIAMONDS = 3
    HEARTS = 4

然后你可以像这样使用它:

Card(Rank.1, Suit.SPADES)

此外,根据以下 Python 文档,它是 ALL_CAPS,甚至在 Class 内。这对我来说也很有意义。

More info and examples.

PEP8 明确表示常量应该是大写的:

Constants

Constants are usually defined on a module level and written in all capital letters with underscores separating words. Examples include MAX_OVERFLOW and TOTAL.

请注意,它只是说这些 通常 在模块级别定义。但是,如果您的值应被视为常量,则将它们设为大写 ​​- 即使它们是在 class 级别上定义的。