Practice content: Use two ways to implement dictionary access attribution: Use a class wrapper dictionary so that the dictionary does not use [] to access the element, use the. Dot number to access the element as if it were a property.
Mode one: direct manipulation of instance dictionaries in __init__
1 __author__='Orcsir'2 3 #Way One4 classattrdict:5 def __init__(self, attrs:dict):6 #direct manipulation of instance dictionaries to avoid the use of magic methods __setattr__7Self.__dict__. Update (ATTRS)8 9 #modifying properties is not allowedTen def __setattr__(self, Key, value): One RaiseNotimplementederror A - - #Test theDCT = {"x": 100,"y": 200} -obj =attrdict (DCT) - Print(obj.x) -obj.x = 900#Error + Print(obj.x, OBJ.Y)
Mode two: Use Metaclass
1 __author__='Orcsir'2 3 classAttrmeta (type):4 def __call__(self, DCT):5 ifDCT = = {}:6 RaiseValueError ("attrdict need non Empty dict")7SetAttr (Self,"__init__",Lambda*Args:none)8obj = Super ().__call__(DCT)9Obj.__dict__. Update (DCT)TenSetAttr (Self,"__setattr__",Lambda*Args:none) One returnobj A - - classAttrdict (Metaclass=attrmeta):Pass the - #Test -DCT = {"x": 100,"y": 200} -obj =attrdict (DCT) + Print(obj.x) -OBJ.Y = 100000#No affect + Print(OBJ.Y)#keep the original value
Basic knowledge of Python programming practice _009