如何使用attrs定义数组对象?

2024-03-28 20:31:58 发布

您现在位置:Python中文网/ 问答频道 /正文

考虑以下数据集:

{
    'name': 'somecat',
    'lives': [
        {'number': 1, 'did': 'nothing'},
        {'number': 2, 'did': 'saved the world'}
    ]
}

我要做的是使用attrs来定义一个数据类,这样即使使用索引号也可以获得自动完成

import attr

@attr.s
class Cat(object):
    name = attr.ib()
    lives: list = [
        {'number': int, 'did': str} # trying to get autocompletion here
    ]


c = Cat('somecat')
print(c)
c.lives[0].number # trying to get autocompletion here

上面的代码是无效的,但这就是我要完成的。你知道吗

我该怎么做呢?我知道metadata,但那是不变的。如果这更有意义的话,我也愿意使用dataclasses。你知道吗


Tags: to数据namenumbergetherecatattr
1条回答
网友
1楼 · 发布于 2024-03-28 20:31:58

诚然,我从来没有真正使用attr模块,而是为了对代码进行最小的更改。我认为在这里使用typing.List也很有用。我个人会使用数据类,但这似乎也很有效

import attr
import typing
from collections import namedtuple

live = namedtuple('live', ['number', 'did'])


@attr.s
class Cat(object):
    name = attr.ib()
    lives: typing.List[live] = attr.ib()


c = Cat('somecat', lives=[live(**{'number': 1, 'did': 'smile'})])
print(c)
c.lives[0].number  # auto completes

只有数据类

import typing
from dataclasses import dataclass


@dataclass
class live:
    number: int
    did: str


@dataclass
class Cat:
    name: str
    lives: typing.List[live]


c = Cat('somecat', lives=[live(**{'number': 1, 'did': 'smile'})])
print(c)
c.lives[0].number  # autocompletes

但是对于嵌套字典,这些数据类可能很困难。就像这样

data = {
    'name': 'somecat',
    'lives': [
        {'number': 1, 'did': 'nothing'},
        {'number': 2, 'did': 'saved the world'}
    ]
}

new_c = Cat(**data)
new_c.lives = [live(**data) for data in new_c.lives]

如果可以的话,我建议调查一下^{}。你知道吗

谢谢

相关问题 更多 >