Python 中的命名常量 class 属性
Naming constant class attribute in Python
我有一个 class 属性,它在 class 中是 常量,但有一个 不同的值在它的子classes 或兄弟classes 中。并且该属性在基 class.
中的方法中使用
在这种情况下,我是否应该将属性 address
表示为常量,即 SCREAMING_SNAKE_CASE 类似于 ADDRESS
?
例如,
class BaseClass:
address = ''
@classmethod
def print_address(cls):
print(cls.address)
class SubClass1(BaseClass):
address = 'sub1'
class SubClass2(BaseClass):
address = 'sub2'
或者,有没有更好的方法来做同样的事情?
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 属性,就 PEP-8 而言,它不被视为常量。
但是,很少有 real-world 例外。
Django 模型的常量
在 Django 文档的示例中,choices
个字段的常量被封装到模型本身中:
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,
)
枚举
enum.Enum
使用 SCREAMING_SNAKE_CASE 作为枚举值。例如:
from enum import Enum
class Color(Enum):
RED = 1
GREEN = 2
BLUE = 3
我有一个 class 属性,它在 class 中是 常量,但有一个 不同的值在它的子classes 或兄弟classes 中。并且该属性在基 class.
中的方法中使用在这种情况下,我是否应该将属性 address
表示为常量,即 SCREAMING_SNAKE_CASE 类似于 ADDRESS
?
例如,
class BaseClass:
address = ''
@classmethod
def print_address(cls):
print(cls.address)
class SubClass1(BaseClass):
address = 'sub1'
class SubClass2(BaseClass):
address = 'sub2'
或者,有没有更好的方法来做同样的事情?
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 属性,就 PEP-8 而言,它不被视为常量。
但是,很少有 real-world 例外。
Django 模型的常量
在 Django 文档的示例中,choices
个字段的常量被封装到模型本身中:
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,
)
枚举
enum.Enum
使用 SCREAMING_SNAKE_CASE 作为枚举值。例如:
from enum import Enum
class Color(Enum):
RED = 1
GREEN = 2
BLUE = 3