我是 Python 新手,不明白为什么我不能这样做。当我尝试从父对象更改 Packet.ItemData 中的值时,它不起作用。请参阅代码中的“不起作用”注释。
import json
from copy import deepcopy
class Event():
__slots__= 'itemName'
def __init__(self, itemName):
self.itemName = itemName
def encode(self):
obj = {}
obj['itemName'] = str(self.itemName)
return json.dumps(obj)
def decode(self, json_Str):
obj = json.loads(json_Str)
self.itemName = obj['itemName']
class Packet():
__slots__= 'pID', 'itemData'
def __init__(self, pID, itemData):
self.pID = pID
self.itemData = itemData
def encode(self):
obj = {}
obj['pID'] = int(self.pID)
obj['itemData'] = str(self.itemData.encode())
return json.dumps(obj)
def decode(self, json_Str):
obj = json.loads(json_Str)
self.pID = obj['pID']
self.itemData = Event(0,'')
defaultEvent = Event('Dflt')
defaultPacket = Packet(1, defaultEvent)
event2 = Event('NoName')
print 'event : ', event2.encode()
packet3 = deepcopy(defaultPacket)
packet3.ItemData = event2; #direct assign doesn't work
packet3.ItemData = deepcopy(event2); #deep copy doesn't work
packet3.ItemData.itemName = 'Hello' #event this doesn't work
print 'packet : ', packet3.encode()
我想包装数据,以便在从 JSON 编码和解码时得到我所期望的。