1, getItem method
Use the biggest impression this is to call the object's attributes can use the same value as the dictionary 中括号['key']
when in use parentheses to object attribute value, or delete the assignment, will automatically trigger a corresponding __getitem__、__setitem__、__delitem__
method
code is as follows:
class Foo(object):
def __init__(self):
self.name = 'jack'
def __getitem__(self,item):
if item in self.__dict__: # item = key,判断该key是否存在对象的 __dict__ 里,
return self.__dict__[item] # 返回该对象 __dict__ 里key对应的value
def __setitem__(self, key, value):
self.__dict__[key] = value # 在对象 __dict__ 为指定的key设置value
def __delitem__(self, key):
del self.__dict__[key] # 在对象 __dict__ 里删除指定的key
f1 = Foo()
print(f1['name']) # jack
f1['age'] =10
print(f1['age']) # 10
del f1['name']
print(f1.__dict__) # {'age': 10}
2, getattr method
When you use an object value, or delete the assignment, it will call the corresponding default __getattr__、__setattr__、__delattr__方法
.
When the value of an object, the value of the order is: start with the object in __getattribute__
the find, from the second step to find the properties of an object, the third step is to find the current class, the fourth step to find from the parent class, the fifth step from __getattr__
in looking for, if not a direct throw an exception.
code show as below:
class Foo(object):
def __init__(self):
self.name = '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(c1.name) # jack
c1.age = 18
print(c1.age) # 18
del c1.age # 删除 对象c1的age
print(c1.age) # None