Section 16: Supplement of Built-in Functions

The built-in functions __getattr__, __setattr__, __delattr__ that will be triggered when the object attributes are obtained, set, and deleted by.


class
Dog:
DEF __init__ ( Self , name , Age):
Self .name = name
Self .age = Age
DEF __getattr__ ( Self , Item): # function in acquiring property does not exist when triggers Print ( "execution is getattr " ) DEF __setattr__ ( self , Key , value): # set object properties when the trigger self . __dict__ [Key] = value DEF __delattr__ ( self , Item): # delete object properties when it will trigger the built-in function self




.__dict__.pop(item)
def run(self):
print("%s今年%s"%(name,age)

 def __getattribute__ ( self , item):   #Execute the function when getting the existing function attribute raise AttributeError ( 'Throw exception' ) #When getting the non-existing function attribute, an exception will be thrown to __getattr__ #__getitem__, __setitem__ __delitem__ built-in functions that will be triggered when accessing, setting, or deleting object attributes by key value
 



class Foo:
def __getitem__(self, item):
print('getitem')
return self.__dict__[item]

def __setitem__(self, key, value):
print('setitem')
self.__dict__[key]=value

def __delitem__(self, key):
print('delitem')
self.__dict__.pop(key)

f1=Foo()
print(f1.__dict__)
f1['name']='sss'
print(f1['name'])

del f1['name']
Execution results are as follows: 
{} setItem getItem sss delItem

Guess you like

Origin www.cnblogs.com/sxdpython/p/12747419.html