我里面有兩個資料類bookmodel,一個繼承自另一個:
@dataclass(frozen=True)
class BookOrder:
category: str
name: str
color: str
price: int
volume: int
@dataclass(frozen=True)
class ClientOrder(BookOrder):
client_id: str
然后在另一個.py檔案中,我需要ClientOrder使用BookOrder以下命令初始化一個實體:
from book_model import BookOrder
# ...
@dataclass
class Client:
id: str
def place_book_order(self, book_order: BookOrder):
# want to init a ClientOrder HERE!!!
由于BookOrder不可呼叫,我無法傳遞self.id給它。我想知道是否有一種優雅的方式來實作這一目標?
更新
猜猜我想問的是,除了下面的方法之外,還有其他方法可以ClientOrder使用初始化BookOrder嗎?
client_order=ClientOrder(book_order.categry, book_order.name, ..., self.client_id)
uj5u.com熱心網友回復:
解決此問題的一種方法是不使用繼承,而是將其宣告client_id為可選屬性。由于BookOrder資料類也被凍結了,然后我們需要呼叫object.__setattr__修改的值client_id,如中提到的這篇文章。
在您的第一個模塊中a.py:
from __future__ import annotations # Added for compatibility with 3.7
from dataclasses import dataclass
@dataclass(frozen=True)
class BookOrder:
category: str
name: str
color: str
price: int
volume: int
client_id: str | None = None
在第二個模塊中b.py:
from book_model import BookOrder
# ...
@dataclass
class Client:
id: str
def place_book_order(self, book_order: BookOrder):
# The following does not work, because BookOrder is a frozen
# dataclass.
# setattr(book_order, 'client_id', self.id)
# Use object.__setattr__ as mentioned here:
# https://stackoverflow.com/a/59249252/10237506
object.__setattr__(book_order, 'client_id', self.id)
if book_order.client_id:
print('Successfully set client_id attribute:',
repr(book_order.client_id))
else:
print('Was unable to set client_id attribute on frozen dataclass')
Client('abc123').place_book_order(BookOrder(*['a'] * 5))
輸出:
Successfully set client_id attribute: 'abc123'
當然,更簡單的方法是不將其定義為frozen資料類:
@dataclass
class BookOrder:
category: str
name: str
color: str
price: int
volume: int
client_id: str | None = None
And then the only change needed in b.py:
...
def place_book_order(self, book_order: BookOrder):
book_order.client_id = self.id
...
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/345008.html
標籤:Python 蟒蛇-3.x 遗产 初始化 python-数据类
