I have a class attribute, which is constant in a class but has a different value in its subclasses or sibling classes . And the attribute is used in a method in the base class.
In this case, should I express the attribute address
as constant, that is, with SCREAMING_SNAKE_CASE like 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.
So, if it's a class attribute, it's not considered as a constant in terms of PEP-8.
However, there are few real-world exceptions.
In examples from Django documentation, constants for choices
of fields are encapsulated into the model itself:
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
enum.Enum
uses SCREAMING_SNAKE_CASE for enum values. For example:
from enum import Enum
class Color(Enum):
RED = 1
GREEN = 2
BLUE = 3
Source: enum.Enum documentation
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.