要实现可订阅对象很简单,只需__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
Run Code Online (Sandbox Code Playgroud)
我知道getattr可以做同样的事情,但我觉得下标访问更优雅.
ken*_*ytm 17
似乎通过改变元类来工作.对于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
Run Code Online (Sandbox Code Playgroud)
在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
Run Code Online (Sandbox Code Playgroud)
小智 13
在课堂上添加以下内容:
class Fruit(object):
def __init__(self):
self.Fruits = {"Apple": 0, "Pear": 1, "Banana": 2}
def __getitem__(self, item):
return self.Fruits[item]
Run Code Online (Sandbox Code Playgroud)
我确实认为您是在询问订阅类而不是类的实例。
这是我对这个问题的回答:“如何在Python中创建可下标的类?”
class Subscriptable:
def __class_getitem__(cls, item):
return cls._get_child_dict()[item]
@classmethod
def _get_child_dict(cls):
return {k: v for k, v in cls.__dict__.items() if not k.startswith('_')}
class Fruits(Subscriptable):
Apple = 0
Pear = 1
Banana = 2
Run Code Online (Sandbox Code Playgroud)
>>> Fruits['Apple']
0
>>> Fruits['Pear']
1
Run Code Online (Sandbox Code Playgroud)
扩展@LuisKleinwort 的答案,如果您想对所有类属性执行此操作:
fruits_dict = {'apple':0, 'banana':1}
class Fruits(object):
def __init__(self, args):
for k in args:
setattr(self, k, args[k])
def __getitem__(self, item):
return getattr(self, item)
fruits = Fruits(fruits_dict)
print(fruits.apple)
print(fruits['apple'])
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
14496 次 |
| 最近记录: |