Python basics such as __setattr__,__delattr__,__getattr__

Source: Internet
Author: User

A __setattr__,__delattr__,__getattr__
    1. __setattr__ #添加/Modify a property will trigger its execution
    2. __delattr__ #删除属性的时候会触发
    3. __getattr__ #只有在调用属性且属性不存在的时候才会触发
classFoo:def __init__(self,x): Self.name=xdef __setattr__(self, Key, value):#if not isinstance (VALUE,STR):        #raise TypeError (' must be str ')        #print ('----setattr---key:%s,value:%s '% (key,value))        #print (Type (key))        #print (type (value))        #Self.key=value        #setattr (Self,key_str,value) #self. Key_attribute=value #这是无限递归Self.__dict__[Key]=value#because you rewrite the __setattr__, any assignment operation will trigger its operation, you do not write anything, is not assigned at all, unless you directly manipulate the property dictionary, otherwise you can never assign a value    def __delattr__(self, item):Print('delattr:%s'%Item)Print(Type (item))#delattr (self,item) #这是无限递归        #del Self.itemSelf.__dict__. Pop (item)#we can directly modify the property dictionary to complete the operation of adding/modifying propertiesF1=foo ('Egon')#f1.name= ' Egon 'F1.age=18Print(F1.__dict__)Print(F1.name)Print(f1.age)Print(F1.__dict__)delF1.agePrint(F1.__dict__)Print(f1.age)#---------------------getattr------------------------classFoo:def __init__(self,x): Self.name=x#Is triggered if the property does not exist    def __getattr__(self, item):Print('getattr-->%s%s'%(Item,type (item))) F=foo ('Egon')#print (f.name)Print(F.XXXXXXX)
Kick Stunt

Python basics such as __setattr__,__delattr__,__getattr__

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.