1、getitem method
The biggest impression of using this method is that calling an object's attributes can be done like a dictionary fetch using the middle bracket ['key']
The __getitem__, __setitem__, and __delitem__ methods are automatically triggered when an attribute in an object is retrieved, assigned, or deleted using the center bracket.
The code is as follows:
class Foo(object): def __init__(self): = 'jack' def __getitem__(self,item): if item in self.__dict__: # item = key, determine if the key exists in the object's __dict__. return self.__dict__[item] # Return the value corresponding to the key in the object's __dict__. def __setitem__(self, key, value): self.__dict__[key] = value # Set the value for the specified key in the object __dict__. def __delitem__(self, key): del self.__dict__[key] # Remove the specified key from the object __dict__. f1 = Foo() print(f1['name']) # jack f1['age'] =10 print(f1['age']) # 10 del f1['name'] print(f1.__dict__) # {'age': 10}
2、getattr method
The __getattr__, __setattr__, and __delattr__ methods are called by default when an object is fetched, assigned, or deleted.
When fetching values from an object, the order of fetching values is as follows: the first step is to look for them in __getattribute__ from the object, the second step is to look for them in the attributes of the object, the third step is to look for them from the current class, the fourth step is to look for them from the parent class, and the fifth step is to look for them from __getattr__, and if they are not there, then an exception will be thrown directly.
The code is as follows:
class Foo(object): def __init__(self): = 'jack' def __getattr__(self, item): if item in self.__dict__: return self.__dict__[item] def __setattr__(self, key, value): self.__dict__[key] = value def __delattr__(self, item): del self.__dict__[item] c1 = Foo() print() # jack = 18 print() # 18 del # Delete the age of object c1 print() # None
This is the whole content of this article.