ディクショナリ内から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のドキュメントには、いくつかの例があります。しかし、私の正確なケースに当てはまるものはありません。
回答
使用する1つの方法は次のとおりです。
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)
必要なすべてのオプションを大文字にする必要がありますか?
それはあなた次第です。それらはすべて大文字にすることができます。これは定数になるため、PEP8に準拠しています。ただし、多くの人は最初の文字だけを大文字にすることを決定し、それはスタイルの有効な選択です。最も一般的でないオプションは、すべて小文字を使用するか、異なる大文字を混合することですが、そうすることを妨げるものは何もありません。完全なリファレンスについては、この回答を参照してください。
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.')
enumクラスの基になる文字列を確認する場合はself.shape.value
、内部を確認する必要がありself.shape
ます。
if self.shape.value == 'circle':
または
if self.shape == ShapeMethod.circle