简体   繁体   English

Python 中的命名常量 class 属性

[英]Naming constant class attribute in Python

I have a class attribute, which is constant in a class but has a different value in its subclasses or sibling classes .我有一个 class 属性,该属性在 class 中是常量,但在其子类或兄弟类中具有不同的值 And the attribute is used in a method in the base class.并且该属性用于基础 class 中的方法中。

In this case, should I express the attribute address as constant, that is, with SCREAMING_SNAKE_CASE like ADDRESS ?在这种情况下,我应该将属性address表示为常量,即使用 SCREAMING_SNAKE_CASE 之类的ADDRESS吗?

For example,例如,

class BaseClass:
    address = ''

    @classmethod
    def print_address(cls):
        print(cls.address)

class SubClass1(BaseClass):
    address = 'sub1'

class SubClass2(BaseClass):
    address = 'sub2'        

Or, is there a better way to do the same thing?或者,有没有更好的方法来做同样的事情?

Constants are usually defined on a module level and written in all capital letters with underscores separating words.常量通常在模块级别定义,并以全大写字母书写,并用下划线分隔单词。 Examples include MAX_OVERFLOW and TOTAL.示例包括 MAX_OVERFLOW 和 TOTAL。

So, if it's a class attribute, it's not considered as a constant in terms of PEP-8.因此,如果它是 class 属性,则在 PEP-8 方面它不被视为常数。

However, there are few real-world exceptions.然而,现实世界中很少有例外。

Constants for Django models Django 型号的常数

In examples from Django documentation, constants for choices of fields are encapsulated into the model itself:在 Django 文档的示例中,用于choices字段的常量被封装到 model 本身中:

class Student(models.Model):
    FRESHMAN = 'FR'
    SOPHOMORE = 'SO'
    JUNIOR = 'JR'
    SENIOR = 'SR'
    GRADUATE = 'GR'
    YEAR_IN_SCHOOL_CHOICES = [
        (FRESHMAN, 'Freshman'),
        (SOPHOMORE, 'Sophomore'),
        (JUNIOR, 'Junior'),
        (SENIOR, 'Senior'),
        (GRADUATE, 'Graduate'),
    ]
    year_in_school = models.CharField(
        max_length=2,
        choices=YEAR_IN_SCHOOL_CHOICES,
        default=FRESHMAN,
    )

Source: Model field reference来源: Model 字段参考

Enums枚举

enum.Enum uses SCREAMING_SNAKE_CASE for enum values. enum.Enum使用 SCREAMING_SNAKE_CASE 作为枚举值。 For example:例如:

from enum import Enum

class Color(Enum):
    RED = 1
    GREEN = 2
    BLUE = 3

Source: enum.Enum documentation来源: enum.Enum 文档

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM