自定义Request类对象无法通过下标访问字典元素问题求助
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

