今天在ASPN上看到有人提到了如何使用__setattr__和__getattr__,算是给自己解了惑,因为一直就没有搞明白这两个函数的用处。
这两个内置函数是用来自定义对象属性的获取方法。__setattr__只能修改对象的instance's attribute,而不能修改class's attribute等等。
该贴的作者以如何把类的attributes映射为dictnary members为例,给出使用这两个方法的一个范例。以下就是该作者的程序:
class attrExample(dict):
def __init__(self, indict=None, attribute=None):
if indict is None:
indict = {}
# 在设置__initialised以前,写attributes的方法还是默认的__setattr
# 也就是说设置的属性都是Normal attributes
self.attribute = attribute
dict.__init__(self, indict)
self.__initialised = True
# 在设置__initialised以后,写入的attributes都将成为字典中的一个Item
def __getattr__(self, item):
# 本函数只有在获取item不是一个“属性”的时候才被调用
# 原因如下:
# Note that if the attribute is found through the normal mechanism,
# __getattr__() is not called. (This is an intentional asymmetry between
# __getattr__() and __setattr__().) This is done both for efficiency
# reasons and because otherwise __setattr__() would have no way to
# access other attributes of the instance. Note that at least for instance
# variables, you can fake total control by not inserting any values in the
# instance attribute dictionary (but instead inserting them in another object).
try:
return self.__getitem__(item)
except KeyError:
raise AttributeError(item)
def __setattr__(self, item, value):
# 设置__initiallised标志
if not self.__dict__.has_key('_attrExample__initialised'):
return dict.__setattr__(self, item, value)
# 这里__dict__表示A dictionary or other mapping object used to store an object's (writable) attributes.
elif self.__dict__.has_key(item):
dict.__setattr__(self, item, value)
# 初始化后,除__dict__中的属性外,都将保存到字典中
else:
self.__setitem__(item, value)