【发布时间】:2019-02-01 23:59:14
【问题描述】:
考虑以下代码示例:
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 对象时,我只知道一个基本位置,例如“内部”或“外部”。只有在那之后,我才能更准确地更新位置。
【问题讨论】:
-
枚举只能有一个值。
-
@juanpa.arrivillaga 啊哈,谢谢。您知道我发布的代码的其他设计选择吗?我认为我想要达到的目标很清楚。
-
这对我来说没有多大意义,但是删除
Inside = 'inside' -
@Jaba 哇,非常感谢。我错过了。
-
从根本上说你所要求的没有意义,任何对象的属性只能有一个值,并且属性不能同时是字符串
'inside'和枚举Inside
标签: python python-3.x