python - 如何使嵌套枚举也有值(value)

标签 python python-3.x

考虑以下代码示例:

from enum import Enum

class Location(Enum):
    Outside = 'outside'
    Inside = 'inside' 
    class Inside(Enum): # TypeError for conflicting names
        Downstairs = 'downstairs'
        Upstairs = 'upstairs'

如何使 Inside 具有“inside”值,同时又是用于访问 Downstairs 和 Upstairs 的嵌套枚举?

所需的输入:

print(Location.Inside)
print(Location.Inside.value)
print(Location.Inside.Downstairs)
print(Location.Inside.Downstairs.value)

期望的输出:

Location.Inside
inside
Location.Inside.Downstairs
downstairs

更新 1:

我的具体问题的更多背景信息:

class Location(Enum):
    Outside = 'outside'
    Inside = 'inside' 
    class Inside(Enum): # TypeError for conflicting names
        Downstairs = 'downstairs'
        Upstairs = 'upstairs'

class Human:
    def __init__(self, location):
        self.location = location

def getLocationFromAPI():
    # this function returns either 'inside' or 'outside'
    # make calls to external API  
    return location # return location from api in str

def whereInside(human):
    if human.location != Location.Inside:
        return None
    # here goes logic that determines if human is downstairs or upstairs
    return locationInside # return either Location.Downstairs or Location.Upstairs


location_str = getLocationFromAPI() # will return 'inside' or 'outside'
location = Location(location_str) # make Enum
human = Human(location) # create human with basic location
if human.location == Location.Inside:
    where_inside = whereInside(human)
    human.location = where_inside # update location to be more precise

问题是当我创建 Human 对象时,我只知道一个基本位置,如“内部”或“外部”。只有在那之后我才能将位置更新得更精确。

最佳答案

您可以通过将 enum.Enum 嵌入到另一个中来完成此操作:(注意名称冲突)

from enum import Enum

class _Inside(Enum):
    Downstairs = 'downstairs'
    Upstairs = 'upstairs'

class Location(Enum):
    Outside = 'outside'
    Inside = _Inside 

print(Location.Inside.value.Downstairs.value)
downstairs

关于python - 如何使嵌套枚举也有值(value),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54488648/

相关文章:

python - 如何检查 PyQt5 在 Mac 上是否正确安装?

python - 使用字典进行字符串压缩

python - 基于人脸识别更新标签

php - C++、Python 或 PHP,无限循环

python - 在 Cartopy、Robinson 投影中绘制直线

python - 嵌套字典理解以避免空值

python - 创建接受 kwargs 的 str(或 int 或 float 或 tuple)的 child

python-3.x - `new_root.mainloop()` 不会使主窗口无响应

python - 我可以访问包含另一个类的对象列表的对象的属性吗

python - 具有复杂 numpy 数组和 native 数据类型的 numba TypingError