英文:
Issue with creation of nested data classes
问题
以下是要翻译的代码部分:
我正在尝试创建嵌套数据类:
```python
from dataclasses import dataclass, field
import datetime
from typing import List
@dataclass
class LineItem:
displayName: str
compareAtPrice: float
discountedPrice: float
pricing: str = field(init=False)
def __post_init__(self):
self.pricing = (
"regular" if self.compareAtPrice == self.discountedPrice else "on sale"
)
@dataclass
class Order:
createdAt: datetime
lineItems: List[LineItem]
def __post_init__(self):
for l in self.lineItems:
LineItem(**l)
data = {
"createdAt": datetime.datetime.now(),
"lineItems": [
{
"displayName": "lineitem 1",
"compareAtPrice": 28.1,
"discountedPrice": 28.1,
},
{
"displayName": "lineitem 2",
"compareAtPrice": 88.1,
"discountedPrice": 78.1,
},
],
}
print(Order(**data))
输出缺少应由class LineItem
中的__post_init__
填充的pricing
字段:
Order(createdAt=datetime.datetime(2023, 3, 9, 17, 18, 40, 136535), lineItems=[{'displayName': 'lineitem 1', 'compareAtPrice': 28.1, 'discountedPrice': 28.1}, {'displayName': 'lineitem 2', 'compareAtPrice': 88.1, 'discountedPrice': 78.1}])
我在这里做错了什么?
<details>
<summary>英文:</summary>
I'm trying to create nested data classes:
from dataclasses import dataclass, field
import datetime
from typing import List
@dataclass
class LineItem:
displayName: str
compareAtPrice: float
discountedPrice: float
pricing: str = field(init=False)
def __post_init__(self):
self.pricing = (
"regular" if self.compareAtPrice == self.discountedPrice else "on sale"
)
@dataclass
class Order:
createdAt: datetime
lineItems: List[LineItem]
def __post_init__(self):
for l in self.lineItems:
LineItem(**l)
data = {
"createdAt": datetime.datetime.now(),
"lineItems": [
{
"displayName": "lineitem 1",
"compareAtPrice": 28.1,
"discountedPrice": 28.1,
},
{
"displayName": "lineitem 2",
"compareAtPrice": 88.1,
"discountedPrice": 78.1,
},
],
}
print(Order(**data))
The output is missing the `pricing` field which should be populated by `__post_init__` in `class LineItem` :
Order(createdAt=datetime.datetime(2023, 3, 9, 17, 18, 40, 136535), lineItems=[{'displayName': 'lineitem 1', 'compareAtPrice': 28.1, 'discountedPrice': 28.1}, {'displayName': 'lineitem 2', 'compareAtPrice': 88.1, 'discountedPrice': 78.1}])
What am I doing wrong here?
</details>
# 答案1
**得分**: 4
你可以在你的 **Order** 类中做一个小改变,如下所示,
```python
@dataclass
class Order:
createdAt: datetime
lineItems: List[LineItem>
def __post_init__(self):
self.lineItems = [LineItem(**l) for l in self.lineItems]
英文:
You can do a small change like this in your Order class,
@dataclass
class Order:
createdAt: datetime
lineItems: List[LineItem]
def __post_init__(self):
self.lineItems = [LineItem(**l) for l in self.lineItems]
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论