如何解决从字典中调用IntEnum类
我有一个示例IntEnum类:
class ShapeMethod(IntEnum):
NONE = 0
circle = 1
square = 2
这需要由另一个类的__init__
函数调用:
class ExampleClass():
def __init__(look_at_shapes=None):
"""
Args:
look_at_shapes (dict): A dictionary of shape inputs.
"""
if look_at_shapes:
self.shape = ShapeMethod.NONE
if look_at_shapes["colour"]:
self.colour = look_at_shapes["colour"]
def do_something_with_shape:
if self.shape == ShapeMethod.circle:
print('awesome you got a circle'.)
elif self.shape == ShapeMethod.square:
print('squares have 4 sides.')
else:
print('nothing to see here.')
其中,self.shape
属性必须为circle
,square
或NONE
。
do_something_with_shape
函数将通过以下方式调用:
input = {"colour" = blue}
my_object = ExampleClass(look_at_shape=input)
my_object.do_something_with_shape
input
的结构必须是字典,并且设置colour
相当简单。但是,我不知道如何从字典内部正确使用IntEnum
类。例如,如果我要打印squares have 4 sides.
注意:ShapeMethod(IntEnum)
中的所有选项是否都必须大写?
到目前为止我所看到的:
Python的documentation给出了许多示例。但是,没有一个适合我的情况。
解决方法
一种使用方式如下:
from enum import IntEnum
class ShapeMethod(IntEnum):
NONE = 0
circle = 1
square = 2
class ExampleClass:
def __init__(self,look_at_shapes=None):
"""
Args:
look_at_shapes (dict): A dictionary of shape inputs.
"""
self.shape = None
self.colour = None
if look_at_shapes:
if look_at_shapes[ShapeMethod]:
self.shape = look_at_shapes[ShapeMethod]
if look_at_shapes["colour"]:
self.colour = look_at_shapes["colour"]
def do_something_with_shape(self):
if self.shape is ShapeMethod.NONE:
print('awesome you got a circle.')
elif self.shape is ShapeMethod.square:
print('squares have 4 sides.')
else:
print('nothing to see here.')
input_var = {
"colour": 'blue',ShapeMethod: ShapeMethod.square
}
my_object = ExampleClass(look_at_shapes=input_var)
my_object.do_something_with_shape()
关于您的附带问题:
注意:
ShapeMethod(IntEnum)
中的所有选项是否都必须大写?
完全取决于您。它们可以全部为大写,这与PEP 8一致,因为它们是常量。但是,很多人决定只使用首字母大写,这是一种有效的样式选择。最不常见的选择是使用所有小写字母或混合使用不同的大小写,但是没有什么可以阻止您这样做。 See this answer for a complete reference.
,input = {
"shape": ShapeMethod.square,"colour": "blue",}
def __init__(look_at_shapes=None):
"""
Args:
look_at_shapes (dict): A dictionary of shape inputs.
"""
look_at_shapes = look_at_shapes or {}
self.shape = look_at_shapes.get("shape",ShapeMethod.NONE)
self.colour = look_at_shapes.get("colour") # None if "colour" doesn't exist
def do_something_with_shape:
if self.shape == ShapeMethod.circle:
print('awesome you got a circle'.)
elif self.shape == ShapeMethod.square:
print('squares have 4 sides.')
else:
print('nothing to see here.')
,
当您要检查枚举类中的基础字符串时,需要检查self.shape.value
的{{1}}的使用情况。
self.shape
或
if self.shape.value == 'circle':
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。