Code: Select all
class Examples_Classes_Singletons :
_Instance = None
def __new__(CLS):
print(
"[ DEBUG ] Creating Class : {} | Line : {} | Module : {}".format(
CLS, CLS.__firstlineno__, CLS.__module__
)
)
if CLS._Instance is None:
print(
f"[ WARNING ] No Instance Found ! Creating Instance For Class '{CLS.__name__}' ..."
)
CLS._Instance = super().__new__(CLS)
__Instance = f""
print(f"[ DEBUG ] Instance : {__Instance}")
return CLS._Instance
def __init__(Self):
# print( Self.__class__.__mro__ == Self.__mro__ )
# print( type( Self ) == Examples_Classes_Singletons )
if "_initialized" in Self.__dict__ and Self._initialized:
print(
f"[ DEBUG ] The Instance Of The Class '{Self.__class__.__name__}' Is Already Initialized !"
)
return
print(f"[ DEBUG ] Configuring Standard Variables ...")
Self.Attribute_X = "TST1" # Instance Variable
Self.Attribute_Y = "TST2" # Instance Variable
Self._Protected_Attribute = {}
Self._Cache = []
# print( object.__getattribute__( Self , 'Attribute_X' ) )
# print( super( ).__getattribute__( 'Attribute_X' ) )
print(
f"[ DEBUG ] Initializing The Instance For Class '{Self.__class__.__name__}' ..."
)
Self._initialized = True
def __getstate__(Self):
State = Self.__dict__.copy()
print(State)
State["_Protected_Attribute"] = None
if "_Cache" in State:
del State["_Cache"]
return State
def __setstate__(Self, State):
Self.__dict__.update(State)
# Self._Cache = { }
if __name__ == "__main__":
pass
T = Examples_Classes_Singletons()
T_Serialized = pickle.dumps(T)
T_Deserialized = pickle.loads(T_Serialized)
print(f"Serialized : {T_Serialized}")
print(f"Deserialized : {T_Deserialized.__dict__}")
Obwohl ich mich tatsächlich an die Richtlinien gehalten habe, wird „_Cache“ nicht gelöscht. Wenn ich die Daten drucke nach:
Code: Select all
print(f"Deserialized : {T_Deserialized.__dict__}")
Code: Select all
Deserialized : {'Attribute_X': 'TST1', 'Attribute_Y': 'TST2', '_Protected_Attribute': None, '_Cache': [], '_initialized': True}
Ist der Code falsch oder habe ich die Syntax von __getstate__ falsch verstanden?