2

考虑从“pydantic”包派生的这个数据类:

from typing import List
from pydantic import BaseModel 
class Bucket(BaseModel):
    setting: List[str]
    fight_1: List[int]
    cause_1: List[str]

让我们my_bucket成为一个实例Bucket

my_bucket = Bucket(setting = ['some_value'], fight_1 = [0], cause_1 = ['other_value'])

基本上我希望能够做到

my_bucket['setting']                                                                                                         

并返回['some_value'],但我得到:

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-18-cacbdc1698e9> in <module>
----> 1 my_bucket['setting']

TypeError: 'Bucket' object is not subscriptable
4

2 回答 2

4

由于您没有定义__init__方法,因此您无法Bucket使用参数实例化 a。所以这是无效的:

my_bucket = Bucket(setting = ['some_value'], fight_1 = [0], cause_1 = ['other_value'])

你可以这样做:

my_bucket = Bucket()
my_bucket.setting = ['some_value']
my_bucket.fight_1 = [0]
my_bucket.cause_1 = ['other_value']

为了达到settingwith my_bucket["setting"],您需要__getitem__在您的类中定义方法:

class Bucket(BaseModel):
    ...
    def __getitem__(self, item):
        return getattr(self, item)

现在你可以做my_bucket["setting"],它会返回:

['some_value']

编辑:我相信以下代码是您真正想要的:

from typing import List
from pydantic import BaseModel

class Bucket(BaseModel):
    def __init__(self, setting: List[str], fight_1: List[int],
                 cause_1: List[str]):
        self.setting = setting
        self.fight_1 = fight_1
        self.cause_1 = cause_1
        super().__init__()

    def __getitem__(self, item):
        return getattr(self, item)


my_bucket = Bucket(setting=['some_value'], fight_1=[0],
                   cause_1=['other_value'])

print(my_bucket['setting'])
于 2020-06-24T17:48:13.477 回答
3

对于 python 数据类,这对我有用:

from dataclasses import dataclass

@dataclass
class MyCustomRequest:
    request: Dict
        
    def __getitem__(self, key):
        return super().__getattribute__(key)
>>> a = MyCustomRequest({"a":10})
>>> a["request"]
{"a":10}
>>> a.request
{"a": 10}
于 2021-02-27T19:15:29.530 回答