避免使用Python Flask和大多数其他语言中的魔术数字

时间:2013-02-28 09:48:50

标签: python database-design python-2.7 refactoring

我正在为我的应用定义模型,我需要一个名为“status”的列用于各种验证过程。这是一个简化的用户模型。

class User
    id(int)
    name(str)
    status(int) # 0- New 1-Active 2-Inactive 3-Reported 4-Deleted

我让Python开发人员检查我的代码;他建议我避免“魔法数字”。他的解决方案是:

class Choices:
    @classmethod
    def get_value(cls, key):
        # get the string display if need to show
        for k, v in cls.CHOICES:
            if k == key:
                return v
        return ""

class UserStatusChoices(Choices):
    NEW = 0
    ACTIVE = 1
    INACTIVE = 2
    REPORTED = 3
    DELETED = 4

    CHOICES = (
        (NEW, "NEW"),
        (ACTIVE, "ACTIVE"),
        (INACTIVE, "INACTIVE"),
        (REPORTED, "REPORTED"),
        (DELETED, "DELETED"),
    )

我不能使用简单的词典吗?有没有人看到'class'y解决方案的充分理由?

1 个答案:

答案 0 :(得分:2)

Python Enum class (with tostring fromstring)

为基础
class Enum(object):
    @classmethod
    def tostring(cls, val):
        for k,v in vars(cls).iteritems():
            if v==val:
                return k

    @classmethod
    def fromstring(cls, str):
        return getattr(cls, str.upper(), None)

    @classmethod
    def build(cls, str):
        for val, name in enumerate(str.split()):
            setattr(cls, name, val)
class MyEnum(Enum):
    VAL1, VAL2, VAL3 = range(3)

class YourEnum(Enum):
    CAR, BOAT, TRUCK = range(3)

class MoreEnum(Enum):
    pass

print MyEnum.fromstring('Val1')
print MyEnum.tostring(2)
print MyEnum.VAL1 

print YourEnum.BOAT
print YourEnum.fromstring('TRUCK')

# Dodgy semantics for creating enums.
# Should really be
# MoreEnum = Enum.build("CIRCLE SQUARE")
MoreEnum.build("CIRCLE SQUARE")
print MoreEnum.CIRCLE
print MoreEnum.tostring(1)
print MoreEnum.tostring(MoreEnum.CIRCLE)

编辑添加了构建类方法,以便可以使用字符串构建枚举。

虽然可能有更好的解决方案。