50

サブスクリプト可能なオブジェクトを実装するのは簡単__getitem__です。このオブジェクトのクラス定義に実装するだけです。
しかし今、私はサブスクリプト可能なクラスを実装したいと思います。たとえば、次のコードを実装したいと思います。

class Fruit(object):
    Apple = 0
    Pear = 1
    Banana = 2
    #________________________________ 
    #/ Some other definitions,         \
    #\ make class 'Fruit' subscriptable. /
    # -------------------------------- 
    #        \   ^__^
    #         \  (oo)\_______
    #            (__)\       )\/\
    #                ||----w |
    #                ||     ||

print Fruit['Apple'], Fruit['Banana']
#Output: 0 2

同じことができることは知ってgetattrいますが、下付き文字へのアクセスの方がエレガントだと思います。

4

4 に答える 4

36

メタクラスを変更することで機能するようです。Python 2 の場合:

class GetAttr(type):
    def __getitem__(cls, x):
        return getattr(cls, x)

class Fruit(object):
    __metaclass__ = GetAttr

    Apple = 0
    Pear = 1
    Banana = 2

print Fruit['Apple'], Fruit['Banana']
# output: 0 2

Python 3 では、Enumを直接使用する必要があります。

import enum

class Fruit(enum.Enum):
    Apple = 0
    Pear = 1
    Banana = 2

print(Fruit['Apple'], Fruit['Banana'])
# Output: Fruit.Apple, Fruit.Banana
print(Fruit['Apple'].value, Fruit['Banana'].value)
# Output: 0 2
于 2012-07-13T11:01:40.887 に答える