■ 메타 클래스를 사용해 자식 클래스에 직렬화/역직렬화 기능을 추가하는 방법을 보여준다.
▶ 예제 코드 (PY)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 |
import json serializableClassDictionary = {} def registerClass(sourceClass): serializableClassDictionary[sourceClass.__name__] = sourceClass class RegisteredSerializableMeta(type): def __new__(metaClass, className, baseClassTuple, classMemberDictionary): classInstance = type.__new__(metaClass, className, baseClassTuple, classMemberDictionary) registerClass(classInstance) return classInstance class Serializable: def __init__(self, *argumentTuple): self.argumentTuple = argumentTuple def serialize(self): return json.dumps( { "className" : self.__class__.__name__, "argumentTuple" : self.argumentTuple, } ) class RegisteredSerializable(Serializable, metaclass = RegisteredSerializableMeta): pass def deserialize(jsonString): jsonDictionary = json.loads(jsonString) className = jsonDictionary["className"] targetClassName = serializableClassDictionary[className] return targetClassName(*jsonDictionary["argumentTuple"]) class Vector3D(RegisteredSerializable): def __init__(self, x, y, z): super().__init__(x, y, z) self.x, self.y, self.z = x, y, z vector = Vector3D(10, -7, 3) jsonString = vector.serialize() print("기존 : ", vector ) print("직렬화 : ", jsonString ) print("역직렬화 : ", deserialize(jsonString)) """ 기존 : <__main__.Vector3D object at 0x7fab3278fb80> 직렬화 : {"className": "Vector3D", "argumentTuple": [10, -7, 3]} 역직렬화 : <__main__.Vector3D object at 0x7fab325d9930> """ |