我希望使用Python中的数据类来创建一个基类和几个派生类。这些类将包含复杂的属性,例如字典。我希望派生类只更改由基类定义的字典的一部分,这可能吗?还是我还是去上普通的老课更好?
代码片段中显示的是当前的情况,这在代码复制方面似乎是浪费的。
在这个例子中,我可以定义一个接受单个参数而不是lambdas的函数,但是在一个真实的例子中,我必须为每个这样的情况定义一个函数,这将是非常麻烦的。
from dataclasses import dataclass, field
@dataclass
class BaseDataClass:
simple_field_one: int = 100
simple_field_two: int = 200
complex_field: dict = field(default_factory=lambda: {
'x': 0.1,
'y': ['a', 'b']
})
@dataclass
class DerivedDataClass(BaseDataClass):
simple_field_two: int = 300 # this is easy
complex_field: dict = field(default_factory=lambda: {
'x': 0.1,
'y': ['a', 'c']
}) # this is wasteful. All I changed was complex_field['y'][1]发布于 2021-03-16 12:47:28
这一点可能是显而易见的,但如果更改非常小,那么使用__post_init__来应用它而不是重新定义字段是很方便的:
from dataclasses import dataclass, field
@dataclass
class BaseDataClass:
simple_field_one: int = 100
simple_field_two: int = 200
complex_field: dict = field(default_factory=lambda: {
'x': 0.1,
'y': ['a', 'b']
})
@dataclass
class DerivedDataClass(BaseDataClass):
simple_field_two: int = 300
def __post_init__(self):
self.complex_field['y'][1] = 'c'如果您希望能够在初始化过程中控制对complex_field的更新,则可能会有稍微不同的选择:
from dataclasses import dataclass, field, InitVar
...
@dataclass
class DerivedDataClass(BaseDataClass):
simple_field_two: int = 300
# having a mutable default is fine here, since its reference isn't kept around
# and we don't change it during post_init
complex_update: InitVar[dict] = {'y': ['a', 'c']}
def __post_init__(self, complex_update):
self.complex_field.update(complex_update)发布于 2021-03-15 18:07:05
我以这种方式广泛地使用数据类型,而且它似乎运行得很好。
然而,我的一个不同之处是将复杂字段作为自己的数据集(请参阅Python nested dataclasses ...is this valid?)。
您可能需要考虑这种方法,看看它如何帮助您减少您正在看到的一些冗长的内容。
https://stackoverflow.com/questions/66640252
复制相似问题