Basic knowledge of Python programming practice _009

Source: Internet
Author: User

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

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.