我注意到一個非常奇怪的行為:
class Aclass:
def __init__(self, time: int, contract: Contract, strategy: str = 'Strategy') -> None:
self.time: int = time
self.contract: Contract = contract
self.strategy: str = strategy
def to_dict(self) -> Dict:
basic = vars(self)
# I don't want this in the result
del basic['contract']
return basic
if __name__ == '__main__':
inst = Aclass(123, Contract())
inst_dict = inst.to_dict()
inst.contract # AttributeError: 'Aclass' object has no attribute 'contract'
我收到上述寫入的屬性錯誤...任何想法為什么會發生這種情況?
如果我使用vars(self).copy()一切正常。
uj5u.com熱心網友回復:
vars(self)__dict__根據以下檔案回傳屬性。回傳的字典存盤了物件實體的所有屬性。因此,洗掉其中一個條目 viadel相當于洗掉物件實體的屬性。
如果要回傳修改vars(self)后的物件而不影響實體,則需要執行復制。
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/331637.html
