如何在Python中实现可订阅类(可订阅类,而不是可订阅对象)?

时间:2021-06-22 16:57:35

To implement a subscriptable object is easy, just implement __getitem__ in this object's class definition.
But now I want to implement a subscriptable class. For example, I want to implement this code:

要实现可订阅对象很简单,只需在此对象的类定义中实现__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

I know getattr can do the same thing, but I feel subscript accessing is more elegant.

我知道getattr可以做同样的事情,但我觉得下标访问更优雅。

2 个解决方案

#1


9  

Seems to work by changing the metaclass. For Python 2:

似乎通过改变元类来工作。对于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

On Python 3, you should use Enum directly:

在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

#2


1  

Add something like this to your class:

在课堂上添加以下内容:

class Fruit(object):
     def __init__(self):
         self.Fruits = {"Apple": 0, "Pear": 1, "Banana": 2}
     def __getitem__(self, item):
         return self.Fruits[item]

#1


9  

Seems to work by changing the metaclass. For Python 2:

似乎通过改变元类来工作。对于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

On Python 3, you should use Enum directly:

在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

#2


1  

Add something like this to your class:

在课堂上添加以下内容:

class Fruit(object):
     def __init__(self):
         self.Fruits = {"Apple": 0, "Pear": 1, "Banana": 2}
     def __getitem__(self, item):
         return self.Fruits[item]