using function attributes as return values

This question already has an answer here:

  • How can I represent an 'Enum' in Python? 43 answers

  • While you can, I wouldn't, especially now that Python has an Enum type in 3.4 which has been backported.

    Your example above might look like this as an Enum :

    class Size(Enum):
    
        small = 1
        medium = 2
        large = 3
    
        @classmethod
        def classify(cls, number):
            if number < 10:
                return cls.small
            elif number < 20:
                return cls.medium
            else:
                return cls.large
    

    In use:

    --> Size.classify(15)
    <Size.medium: 2>
    

    namedtuple ,也许?

    >>> from collections import namedtuple
    >>> 
    >>> SizeSpec = namedtuple('SizeSpec', ['small', 'medium', 'large'])
    >>> 
    >>> size = SizeSpec(small=1, medium=2, large=3)
    >>> 
    >>> size.small
    1
    >>> size.medium
    2
    >>> size.large
    3
    
    链接地址: http://www.djcxy.com/p/91742.html

    上一篇: Python中的C ++枚举实例

    下一篇: 使用函数属性作为返回值