You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

自定义Request类对象无法通过下标访问字典元素问题求助

Fixing the 'Request' object is not subscriptable Error

Let's break down what's happening here and how to fix it quickly.

The Root Cause

When you try to access request['b'], Python expects your Request class to support subscript access (like dictionaries or lists do). By default, custom Python classes don't come with this behavior—you have to explicitly add the methods that enable it.

Your Original Code (for reference)

data = { 'a': { 'vsdf': 'asfas', 'nfgn': 'aser', 'aser': 'rtydf' }, 'b': ['ndfg', 'ndf', 'safd'] }

class Request:
    def __init__(self, meta):
        self.meta = meta

request = Request(data)
print(request['b'])  # Throws: 'Request' object is not subscriptable

Solution 1: Implement the __getitem__ Method

Add this special method to your Request class to enable subscript access. It tells Python what to do when you use [] on an instance of your class:

class Request:
    def __init__(self, meta):
        self.meta = meta
    
    def __getitem__(self, key):
        # Delegate the lookup to the underlying meta dictionary
        return self.meta[key]

request = Request(data)
print(request['b'])  # Output: ['ndfg', 'ndf', 'safd']

If you also need to set values using subscript syntax (like request['b'] = ['new', 'values']), add the __setitem__ method too:

def __setitem__(self, key, value):
    self.meta[key] = value

Solution 2: Directly Access the meta Attribute

If you don't need the subscript syntax, you can just access the dictionary through the meta attribute directly. This is simpler if you don't need to mimic dictionary behavior:

print(request.meta['b'])  # Output: ['ndfg', 'ndf', 'safd']

Either approach will get you the expected result. Pick the one that fits how you want to interact with your Request objects!

内容的提问来源于stack exchange,提问作者Prithvi Singh

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.14 07:10:04