社区所有版块导航
Python
python开源   Django   Python   DjangoApp   pycharm  
DATA
docker   Elasticsearch  
aigc
aigc   chatgpt  
WEB开发
linux   MongoDB   Redis   DATABASE   NGINX   其他Web框架   web工具   zookeeper   tornado   NoSql   Bootstrap   js   peewee   Git   bottle   IE   MQ   Jquery  
机器学习
机器学习算法  
Python88.com
反馈   公告   社区推广  
产品
短视频  
印度
印度  
Py学习  »  Python

使用Python,有没有一种方法可以让Class[key]从静态容器中提取出来?

OstermanA • 4 年前 • 1665 次点击  

我正在尝试构建一个类,该类维护该类所有对象的内部列表,并可以通过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"])
Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/132562
文章 [ 1 ]  |  最新文章 4 年前
martineau
Reply   •   1 楼
martineau    5 年前

关于你的 编辑 如果使用元类,我建议使用 dict 而不是 set 对于 bucket

class MetaBucket(type):
    def __init__(cls, name, bases, dct):
        cls.bucket = {}

    def __getitem__(cls, id):
        return cls.bucket[id]

    def __setitem__(cls, id, name):
        cls.bucket[id] = name


class Bucket(metaclass=MetaBucket):
    def __init__(self, id, name):
        self.bucket[id] = name


b = Bucket("foo", "bar")
print(3, Bucket["foo"])  # -> 3 bar
print(4, Bucket["nonesuch"])  # -> KeyError: 'nonesuch'