我正在尝试构建一个类,该类维护该类所有对象的内部列表,并可以通过ID查找它们
myClass.get(objectID)
为了得到这些物品,我更愿意使用
myClass[objectID]
但是这个
TypeError: 'type' object is not subscriptable
.下面的示例案例是否有可行的排列方式?
class Bucket(object):
bucket = set()
def __init__(self, id, name):
self.id = id
self.name = name
Bucket.bucket.add(self)
def get(id):
return Bucket.__getitem__(None, id)
def __getitem__(self, id):
for i in Bucket.bucket:
if i.id == id:
return i.name
return None
b = Bucket("foo", "bar")
print(1, Bucket.get("foo"))
print(2, b["foo"])
print(3, Bucket["foo"])
1 bar
2 bar
Traceback (most recent call last):
File "{snip}\bucketTest.py", line 22, in <module>
print(3, Bucket["foo"])
TypeError: 'type' object is not subscriptable
编辑
通过对元类方向的提示,我想到了这个。老实说,我以前从未遇到过这样的问题,我不得不问:我这样做对吗?我是否遗漏了一些基本点,或者这是模糊正确的?我该如何改进它?
class MetaBucket(type):
def __init__(cls, name, bases, dct):
cls.bucket = set()
def __getitem__(cls, key):
for i in cls.bucket:
if i.id == key:
return i.name
class Bucket(metaclass = MetaBucket):
def __init__(self, id, name):
self.id = id
self.name = name
Bucket.bucket.add(self)
b = Bucket("foo", "bar")
print(3, Bucket["foo"])