Python 3.4以降、Enum
クラスが存在します。Pythonで列挙型を比較するには?
私はいくつかの定数は、特定の順序を持っていると私はそれらを比較するのが最も神託のある方法だろプログラムを書いています:
class Information(Enum):
ValueOnly = 0
FirstDerivative = 1
SecondDerivative = 2
今与えられたを比較する必要がある方法があるinformation
異なる列挙型とInformation
の:
information = Information.FirstDerivative
print(value)
if information >= Information.FirstDerivative:
print(jacobian)
if information >= Information.SecondDerivative:
print(hessian)
は、直接の比較は、列挙型では動作しませんので、3つのアプローチがあると私は1つが優先されるだろう。
アプローチ1:使用値:
if information.value >= Information.FirstDerivative.value:
...
はアプローチ2:使用IntEnum:
class Information(IntEnum):
...
アプローチ3:すべての列挙型を使用していない:
class Information:
ValueOnly = 0
FirstDerivative = 1
SecondDerivative = 2
各アプローチは動作しますが、アプローチアプローチ2は推奨されていないIntEnumクラスを使用し、アプローチ3はEnumが追加される前の方法です。
私はアプローチ1を使用する傾向がありますが、わかりません。
ありがとうございました!
すばらしい説明、ありがとう。あなたは 'raise NotImplemented'の代わりに' NotImplemented'を返します。通常のルールはありますか?いつリターンを使用するのですか? –
@SebastianWerkさて、例外ではないので、NotImplementedを呼び出すことはできません。これはビルトインシングルトンです。 [docs](https://docs.python.org/3.5/library/constants.html#NotImplemented)を参照してください。リッチ比較演算子の特別なケースがあります。 [docs](https://docs.python.org/2/library/exceptions.html#exceptions.NotImplementedError)によると、「NotImplementedError」は、「抽象メソッドは、派生が必要なときにこの例外を発生させるべきときメソッドをオーバーライドするクラス。 "。 –
@SebastianWerkまた、この質問を参照してください:http://stackoverflow.com/questions/878943/why-return-notimplemented-instead-of-raising-notimplementederror –