__setattr__和__getattr__的使用

今天在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)


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值